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.

refactor(backend): move the block and file-upload routes into features/blocks (#14478)

Reinier van der Leerf6177ae44c3f
diff --git a/autogpt_platform/backend/backend/api/features/blocks/__init__.py b/autogpt_platform/backend/backend/api/features/blocks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/api/features/blocks/routes.py b/autogpt_platform/backend/backend/api/features/blocks/routes.py
new file mode 100644
index 0000000000..4f69d88179
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/blocks/routes.py
@@ -0,0 +1,262 @@
+import base64
+import time
+from collections import defaultdict
+from typing import Annotated
+
+from autogpt_libs.auth import get_request_context, get_user_id, requires_user
+from autogpt_libs.auth.models import RequestContext
+from fastapi import (
+ APIRouter,
+ Depends,
+ File,
+ HTTPException,
+ Response,
+ Security,
+ UploadFile,
+)
+from fastapi.concurrency import run_in_threadpool
+from pydantic import BaseModel
+from starlette.status import HTTP_402_PAYMENT_REQUIRED
+
+from backend.api.model import UploadFileResponse
+from backend.blocks import get_block, get_blocks
+from backend.copilot.rate_limit import enforce_payment_paywall
+from backend.data.block import BlockInput, CompletedBlockOutput
+from backend.data.execution import ExecutionContext
+from backend.data.user import get_user_by_id
+from backend.executor import utils as execution_utils
+from backend.monitoring.instrumentation import record_block_execution
+from backend.util.cache import cached
+from backend.util.cloud_storage import get_cloud_storage_handler
+from backend.util.exceptions import InsufficientBalanceError
+from backend.util.json import dumps
+from backend.util.settings import Settings
+from backend.util.timezone_utils import get_user_timezone_or_utc
+from backend.util.virus_scanner import scan_content_safe
+
+settings = Settings()
+
+# Tags stay per-route: two are "blocks" and the upload is "files".
+# execute_graph_block keeps its extra Depends(enforce_payment_paywall).
+router = APIRouter(dependencies=[Security(requires_user)])
+
+
+def _compute_blocks_sync() -> str:
+ """
+ Synchronous function to compute blocks data.
+ This does the heavy lifting: instantiate 226+ blocks, compute costs, serialize.
+ """
+ from backend.data.credit import get_block_cost
+
+ block_classes = get_blocks()
+ result = []
+
+ for block_class in block_classes.values():
+ block_instance = block_class()
+ if not block_instance.disabled:
+ costs = get_block_cost(block_instance)
+ # Convert BlockCost BaseModel objects to dictionaries for JSON serialization
+ costs_dict = [
+ cost.model_dump() if isinstance(cost, BaseModel) else cost
+ for cost in costs
+ ]
+ result.append({**block_instance.to_dict(), "costs": costs_dict})
+
+ # Use our JSON utility which properly handles complex types through to_dict conversion
+ return dumps(result)
+
+
+@cached(ttl_seconds=3600)
+async def _get_cached_blocks() -> str:
+ """
+ Async cached function with thundering herd protection.
+ On cache miss: runs heavy work in thread pool
+ On cache hit: returns cached string immediately (no thread pool needed)
+ """
+ # Only run in thread pool on cache miss - cache hits return immediately
+ return await run_in_threadpool(_compute_blocks_sync)
+
+
+ path="/blocks",
+ summary="List available blocks",
+ tags=["blocks"],
+ responses={
+ 200: {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": {"additionalProperties": True, "type": "object"},
+ "type": "array",
+ "title": "Response Getv1List Available Blocks",
+ }
+ }
+ },
+ }
+ },
+)
+async def get_graph_blocks() -> Response:
+ # Cache hit: returns immediately, Cache miss: runs in thread pool
+ content = await _get_cached_blocks()
+ return Response(
+ content=content,
+ media_type="application/json",
+ )
+
+
+ path="/blocks/{block_id}/execute",
+ summary="Execute graph block",
+ tags=["blocks"],
+ dependencies=[Depends(enforce_payment_paywall)],
+ responses={
+ 402: {"description": "Subscription required (NO_TIER user, paywall on)"},
+ },
+)
+async def execute_graph_block(
+ block_id: str,
+ data: BlockInput,
+ user_id: Annotated[str, Security(get_user_id)],
+ ctx: Annotated[RequestContext, Security(get_request_context)],
+) -> CompletedBlockOutput:
+ obj = get_block(block_id)
+ if not obj:
+ raise HTTPException(status_code=404, detail=f"Block #{block_id} not found.")
+ if obj.disabled:
+ raise HTTPException(status_code=403, detail=f"Block #{block_id} is disabled.")
+
+ user = await get_user_by_id(user_id)
+ if not user:
+ raise HTTPException(status_code=404, detail="User not found.")
+
+ try:
+ await execution_utils.charge_for_direct_block_execution(
+ user_id=user_id, block=obj, input_data=data, source="internal"
+ )
+ except InsufficientBalanceError as e:
+ raise HTTPException(status_code=HTTP_402_PAYMENT_REQUIRED, detail=str(e)) from e
+
+ # Direct block execution has no graph; build a minimal ExecutionContext
+ # carrying the caller's identity + timezone so blocks that depend on
+ # those (e.g. time blocks) get correct data.
+ execution_context = ExecutionContext(
+ user_id=user_id,
+ user_timezone=get_user_timezone_or_utc(user.timezone),
+ )
+
+ start_time = time.time()
+ try:
+ output = defaultdict(list)
+ async for name, data in obj.execute(
+ data,
+ user_id=user_id,
+ execution_context=execution_context,
+ ):
+ output[name].append(data)
+
+ # Record successful block execution with duration
+ duration = time.time() - start_time
+ block_type = obj.__class__.__name__
+ record_block_execution(
+ block_type=block_type, status="success", duration=duration
+ )
+
+ return output
+ except Exception:
+ # Record failed block execution
+ duration = time.time() - start_time
+ block_type = obj.__class__.__name__
+ record_block_execution(block_type=block_type, status="error", duration=duration)
+ raise
+
+
+ path="/files/upload",
+ summary="Upload file to cloud storage",
+ tags=["files"],
+)
+async def upload_file(
+ user_id: Annotated[str, Security(get_user_id)],
+ ctx: Annotated[RequestContext, Security(get_request_context)],
+ file: UploadFile = File(...),
+ expiration_hours: int = 24,
+) -> UploadFileResponse:
+ """
+ Upload a file to cloud storage and return a storage key that can be used
+ with FileStoreBlock and AgentFileInputBlock.
+
+ Args:
+ file: The file to upload
+ user_id: The user ID
+ expiration_hours: Hours until file expires (1-48)
+
+ Returns:
+ Dict containing the cloud storage path and signed URL
+ """
+ if expiration_hours < 1 or expiration_hours > 48:
+ raise HTTPException(
+ status_code=400, detail="Expiration hours must be between 1 and 48"
+ )
+
+ # Check file size limit before reading content to avoid memory issues
+ max_size_mb = settings.config.upload_file_size_limit_mb
+ max_size_bytes = max_size_mb * 1024 * 1024
+
+ # Try to get file size from headers first
+ if hasattr(file, "size") and file.size is not None and file.size > max_size_bytes:
+ raise _create_file_size_error(file.size, max_size_mb)
+
+ # Read file content
+ content = await file.read()
+ content_size = len(content)
+
+ # Double-check file size after reading (in case header was missing/incorrect)
+ if content_size > max_size_bytes:
+ raise _create_file_size_error(content_size, max_size_mb)
+
+ # Extract common variables
+ file_name = file.filename or "uploaded_file"
+ content_type = file.content_type or "application/octet-stream"
+
+ # Virus scan the content
+ await scan_content_safe(content, filename=file_name)
+
+ # Check if cloud storage is configured
+ cloud_storage = await get_cloud_storage_handler()
+ if not cloud_storage.config.gcs_bucket_name:
+ # Fallback to base64 data URI when GCS is not configured
+ base64_content = base64.b64encode(content).decode("utf-8")
+ data_uri = f"data:{content_type};base64,{base64_content}"
+
+ return UploadFileResponse(
+ file_uri=data_uri,
+ file_name=file_name,
+ size=content_size,
+ content_type=content_type,
+ expires_in_hours=expiration_hours,
+ )
+
+ # Store in cloud storage
+ storage_path = await cloud_storage.store_file(
+ content=content,
+ filename=file_name,
+ expiration_hours=expiration_hours,
+ user_id=user_id,
+ )
+
+ return UploadFileResponse(
+ file_uri=storage_path,
+ file_name=file_name,
+ size=content_size,
+ content_type=content_type,
+ expires_in_hours=expiration_hours,
+ )
+
+
+def _create_file_size_error(size_bytes: int, max_size_mb: int) -> HTTPException:
+ """Create standardized file size error response."""
+ return HTTPException(
+ status_code=400,
+ detail=f"File size ({size_bytes} bytes) exceeds the maximum allowed size of {max_size_mb}MB",
+ )
diff --git a/autogpt_platform/backend/backend/api/features/blocks/routes_test.py b/autogpt_platform/backend/backend/api/features/blocks/routes_test.py
new file mode 100644
index 0000000000..b7d3cdd47e
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/blocks/routes_test.py
@@ -0,0 +1,635 @@
+"""Tests for the block and file-upload routes."""
+
+import json
+from io import BytesIO
+from unittest.mock import AsyncMock, Mock, patch
+
+import fastapi
+import fastapi.testclient
+import pytest
+import pytest_mock
+import starlette.datastructures
+from autogpt_libs.auth.models import RequestContext
+from fastapi import HTTPException, UploadFile
+from fastapi.routing import APIRoute
+from pytest_snapshot.plugin import Snapshot
+
+from backend.api.features.blocks.routes import router, upload_file
+from backend.api.rest_api import app as real_app
+from backend.util.exceptions import InsufficientBalanceError
+
+
+def _test_ctx(user_id: str) -> RequestContext:
+ return RequestContext(
+ user_id=user_id,
+ org_id="test-org",
+ team_id="test-workspace",
+ is_org_owner=True,
+ is_org_admin=True,
+ is_org_billing_manager=False,
+ is_team_admin=True,
+ is_team_billing_manager=False,
+ seat_status="ACTIVE",
+ )
+
+
+app = fastapi.FastAPI()
+app.include_router(router)
+client = fastapi.testclient.TestClient(app)
+
+
[email protected](autouse=True)
+def setup_app_auth(mock_jwt_user, test_user_id):
+ from autogpt_libs.auth.dependencies import get_request_context
+ from autogpt_libs.auth.jwt_utils import get_jwt_payload
+ from autogpt_libs.auth.models import RequestContext
+
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+
+ async def _fake_request_context() -> RequestContext:
+ return RequestContext(
+ user_id=test_user_id,
+ org_id="test-org",
+ team_id=None,
+ is_org_owner=True,
+ is_org_admin=True,
+ is_org_billing_manager=False,
+ is_team_admin=True,
+ is_team_billing_manager=False,
+ seat_status="ACTIVE",
+ )
+
+ app.dependency_overrides[get_request_context] = _fake_request_context
+ yield
+ app.dependency_overrides.clear()
+
+
+# Tags differ across the three, so they stay per-route and the mount supplies
+# only ["v1"]; execute keeps its paywall on top of the router's auth.
+EXPECTED_OPERATIONS = {
+ ("get", "/api/blocks"): ["v1", "blocks"],
+ ("post", "/api/blocks/{block_id}/execute"): ["v1", "blocks"],
+ ("post", "/api/files/upload"): ["v1", "files"],
+}
+
+
+ "method,path,tags", [(m, p, t) for (m, p), t in EXPECTED_OPERATIONS.items()]
+)
+def test_block_operation_is_published(method: str, path: str, tags: list[str]):
+ operation = real_app.openapi()["paths"][path][method]
+ assert operation["tags"] == tags
+
+
[email protected]("path", sorted({p for _, p in EXPECTED_OPERATIONS}))
+def test_block_route_requires_an_authenticated_user(path: str):
+ """`security` in the schema does not prove this — each handler's own
+ Security(get_user_id) puts it there. Assert the dependency."""
+ for route in real_app.routes:
+ if isinstance(route, APIRoute) and route.path == path:
+ assert "requires_user" in {
+ d.call.__name__ for d in route.dependant.dependencies if d.call
+ }
+
+
+def test_execute_block_is_behind_the_payment_paywall():
+ """The only one of the three with a dependency beyond auth, and it gates
+ spending."""
+ route = next(
+ r
+ for r in real_app.routes
+ if isinstance(r, APIRoute) and r.path == "/api/blocks/{block_id}/execute"
+ )
+ assert "enforce_payment_paywall" in {
+ d.call.__name__ for d in route.dependant.dependencies if d.call
+ }
+
+
+def test_block_surface_has_no_other_operations():
+ served = {
+ (method.lower(), route.path)
+ for route in real_app.routes
+ if isinstance(route, APIRoute)
+ and route.endpoint.__module__ == "backend.api.features.blocks.routes"
+ for method in route.methods
+ if method != "HEAD"
+ }
+ assert served == set(EXPECTED_OPERATIONS)
+
+
+def test_get_graph_blocks(
+ mocker: pytest_mock.MockFixture,
+ snapshot: Snapshot,
+) -> None:
+ """Test get blocks endpoint"""
+ # Mock block
+ mock_block = Mock()
+ mock_block.to_dict.return_value = {
+ "id": "test-block",
+ "name": "Test Block",
+ "description": "A test block",
+ "disabled": False,
+ }
+ mock_block.id = "test-block"
+ mock_block.disabled = False
+
+ # Mock get_blocks
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_blocks",
+ return_value={"test-block": lambda: mock_block},
+ )
+
+ # Mock block costs
+ mocker.patch(
+ "backend.data.credit.get_block_cost",
+ return_value=[{"cost": 10, "type": "credit"}],
+ )
+
+ response = client.get("/blocks")
+
+ assert response.status_code == 200
+ response_data = response.json()
+ assert len(response_data) == 1
+ assert response_data[0]["id"] == "test-block"
+
+ snapshot.snapshot_dir = "snapshots"
+ snapshot.assert_match(
+ json.dumps(response_data, indent=2, sort_keys=True),
+ "blks_all",
+ )
+
+
+def test_execute_graph_block(
+ mocker: pytest_mock.MockFixture,
+ snapshot: Snapshot,
+) -> None:
+ """Test execute block endpoint"""
+ # Mock block
+ mock_block = Mock()
+ mock_block.disabled = False
+ mock_block.name = "TestBlock"
+
+ async def mock_execute(*args, **kwargs):
+ yield "output1", {"data": "result1"}
+ yield "output2", {"data": "result2"}
+
+ mock_block.execute = mock_execute
+
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_block",
+ return_value=mock_block,
+ )
+
+ # Mock user for user_context
+ mock_user = Mock()
+ mock_user.timezone = "UTC"
+
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_user_by_id",
+ return_value=mock_user,
+ )
+
+ # Default to free block: cost = 0, no charge call. The credit model is
+ # patched where the charge would actually go through — the sibling
+ # charging test below patches the same target — so "not awaited" is a
+ # claim about the code path rather than about an unrelated mock.
+ cost_mock = mocker.patch(
+ "backend.api.features.blocks.routes.execution_utils.block_usage_cost",
+ return_value=(0, {}),
+ )
+ mock_credit_model = mocker.AsyncMock()
+ mocker.patch(
+ "backend.executor.utils.get_user_credit_model",
+ return_value=mock_credit_model,
+ )
+ request_data = {
+ "input_name": "test_input",
+ "input_value": "test_value",
+ }
+
+ response = client.post("/blocks/test-block/execute", json=request_data)
+
+ assert response.status_code == 200
+ response_data = response.json()
+
+ # Cost = 0 path: no spend_credits call.
+ cost_mock.assert_called_once()
+ mock_credit_model.spend_credits.assert_not_awaited()
+
+ snapshot.snapshot_dir = "snapshots"
+ snapshot.assert_match(
+ json.dumps(response_data, indent=2, sort_keys=True),
+ "blks_exec",
+ )
+
+
+def test_execute_graph_block_forwards_execution_context(
+ mocker: pytest_mock.MockFixture,
+ test_user_id: str,
+) -> None:
+ """Regression for #12648: blocks that read execution_context (e.g. time
+ blocks) crashed because the direct-block-execute route didn't forward
+ one. The route must construct an ExecutionContext carrying the caller's
+ user_id + timezone and pass it through to ``Block.execute``."""
+ captured_kwargs: dict = {}
+
+ mock_block = Mock()
+ mock_block.disabled = False
+ mock_block.name = "TestBlock"
+
+ async def mock_execute(*args, **kwargs):
+ captured_kwargs.update(kwargs)
+ yield "output", {"data": "ok"}
+
+ mock_block.execute = mock_execute
+
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_block",
+ return_value=mock_block,
+ )
+
+ mock_user = Mock()
+ mock_user.timezone = "America/New_York"
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_user_by_id",
+ return_value=mock_user,
+ )
+
+ mocker.patch(
+ "backend.api.features.blocks.routes.execution_utils.block_usage_cost",
+ return_value=(0, {}),
+ )
+
+ response = client.post("/blocks/test-block/execute", json={"x": "y"})
+
+ assert response.status_code == 200
+ assert "execution_context" in captured_kwargs
+ ctx = captured_kwargs["execution_context"]
+ assert ctx.user_id == test_user_id
+ assert ctx.user_timezone == "America/New_York"
+
+
+def test_execute_graph_block_charges_when_cost_positive(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Paid blocks must charge credits before executing."""
+ mock_block = Mock()
+ mock_block.disabled = False
+ mock_block.id = "paid-block"
+ mock_block.name = "PaidBlock"
+
+ async def mock_execute(*args, **kwargs):
+ yield "output", {"data": "ok"}
+
+ mock_block.execute = mock_execute
+
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_block",
+ return_value=mock_block,
+ )
+ mock_user = Mock()
+ mock_user.timezone = "UTC"
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_user_by_id",
+ return_value=mock_user,
+ )
+
+ cost_filter = {"model": "gpt-4"}
+ mocker.patch(
+ "backend.executor.utils.block_usage_cost",
+ return_value=(42, cost_filter),
+ )
+ mock_credit_model = mocker.AsyncMock()
+ mocker.patch(
+ "backend.executor.utils.get_user_credit_model",
+ return_value=mock_credit_model,
+ )
+
+ response = client.post(
+ "/blocks/paid-block/execute", json={"input_name": "x", "input_value": "y"}
+ )
+
+ assert response.status_code == 200
+ mock_credit_model.spend_credits.assert_awaited_once()
+ call_kwargs = mock_credit_model.spend_credits.await_args.kwargs
+ assert call_kwargs["cost"] == 42
+ metadata = call_kwargs["metadata"]
+ assert metadata.block_id == "paid-block"
+ assert metadata.block == "PaidBlock"
+ assert metadata.input == cost_filter
+ assert metadata.reason == "Direct internal block execution of PaidBlock"
+
+
+def test_execute_graph_block_returns_402_on_insufficient_balance(
+ mocker: pytest_mock.MockFixture,
+ test_user_id: str,
+) -> None:
+ """If spend_credits raises InsufficientBalanceError, endpoint returns 402."""
+ mock_block = Mock()
+ mock_block.disabled = False
+ mock_block.id = "paid-block"
+ mock_block.name = "PaidBlock"
+ mock_block.execute = AsyncMock()
+
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_block",
+ return_value=mock_block,
+ )
+ mock_user = Mock()
+ mock_user.timezone = "UTC"
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_user_by_id",
+ return_value=mock_user,
+ )
+ mocker.patch(
+ "backend.executor.utils.block_usage_cost",
+ return_value=(99, {}),
+ )
+
+ mock_credit_model = mocker.AsyncMock()
+ mock_credit_model.spend_credits.side_effect = InsufficientBalanceError(
+ message="Insufficient balance",
+ user_id=test_user_id,
+ balance=10,
+ amount=99,
+ )
+ mocker.patch(
+ "backend.executor.utils.get_user_credit_model",
+ return_value=mock_credit_model,
+ )
+
+ response = client.post(
+ "/blocks/paid-block/execute", json={"input_name": "x", "input_value": "y"}
+ )
+
+ assert response.status_code == 402
+ mock_block.execute.assert_not_called()
+
+
+def test_execute_graph_block_not_found(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Test execute block with non-existent block"""
+ mocker.patch(
+ "backend.api.features.blocks.routes.get_block",
+ return_value=None,
+ )
+
+ response = client.post("/blocks/nonexistent-block/execute", json={})
+
+ assert response.status_code == 404
+ assert "not found" in response.json()["detail"]
+
+
+async def test_upload_file_success(test_user_id: str):
+ """Test successful file upload."""
+ # Create mock upload file
+ file_content = b"test file content"
+ file_obj = BytesIO(file_content)
+ upload_file_mock = UploadFile(
+ filename="test.txt",
+ file=file_obj,
+ headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
+ )
+
+ # Mock dependencies
+ with (
+ patch("backend.api.features.blocks.routes.scan_content_safe") as mock_scan,
+ patch(
+ "backend.api.features.blocks.routes.get_cloud_storage_handler"
+ ) as mock_handler_getter,
+ ):
+ mock_scan.return_value = None
+ mock_handler = AsyncMock()
+ mock_handler.store_file.return_value = "gcs://test-bucket/uploads/123/test.txt"
+ mock_handler_getter.return_value = mock_handler
+
+ # Mock file.read()
+ upload_file_mock.read = AsyncMock(return_value=file_content)
+
+ result = await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ expiration_hours=24,
+ )
+
+ # Verify result
+ assert result.file_uri == "gcs://test-bucket/uploads/123/test.txt"
+ assert result.file_name == "test.txt"
+ assert result.size == len(file_content)
+ assert result.content_type == "text/plain"
+ assert result.expires_in_hours == 24
+
+ # Verify virus scan was called
+ mock_scan.assert_called_once_with(file_content, filename="test.txt")
+
+ # Verify cloud storage operations
+ mock_handler.store_file.assert_called_once_with(
+ content=file_content,
+ filename="test.txt",
+ expiration_hours=24,
+ user_id=test_user_id,
+ )
+
+
+async def test_upload_file_no_filename(test_user_id: str):
+ """Test file upload without filename."""
+ file_content = b"test content"
+ file_obj = BytesIO(file_content)
+ upload_file_mock = UploadFile(
+ filename=None,
+ file=file_obj,
+ headers=starlette.datastructures.Headers(
+ {"content-type": "application/octet-stream"}
+ ),
+ )
+
+ with (
+ patch("backend.api.features.blocks.routes.scan_content_safe") as mock_scan,
+ patch(
+ "backend.api.features.blocks.routes.get_cloud_storage_handler"
+ ) as mock_handler_getter,
+ ):
+ mock_scan.return_value = None
+ mock_handler = AsyncMock()
+ mock_handler.store_file.return_value = (
+ "gcs://test-bucket/uploads/123/uploaded_file"
+ )
+ mock_handler_getter.return_value = mock_handler
+
+ upload_file_mock.read = AsyncMock(return_value=file_content)
+
+ result = await upload_file(
+ file=upload_file_mock, user_id=test_user_id, ctx=_test_ctx(test_user_id)
+ )
+
+ assert result.file_name == "uploaded_file"
+ assert result.content_type == "application/octet-stream"
+
+ # Verify virus scan was called with default filename
+ mock_scan.assert_called_once_with(file_content, filename="uploaded_file")
+
+
+async def test_upload_file_invalid_expiration(test_user_id: str):
+ """Test file upload with invalid expiration hours."""
+ file_obj = BytesIO(b"content")
+ upload_file_mock = UploadFile(
+ filename="test.txt",
+ file=file_obj,
+ headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
+ )
+
+ # Test expiration too short
+ with pytest.raises(HTTPException) as exc_info:
+ await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ expiration_hours=0,
+ )
+ assert exc_info.value.status_code == 400
+ assert "between 1 and 48" in exc_info.value.detail
+
+ # Test expiration too long
+ with pytest.raises(HTTPException) as exc_info:
+ await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ expiration_hours=49,
+ )
+ assert exc_info.value.status_code == 400
+ assert "between 1 and 48" in exc_info.value.detail
+
+
+async def test_upload_file_virus_scan_failure(test_user_id: str):
+ """Test file upload when virus scan fails."""
+ file_content = b"malicious content"
+ file_obj = BytesIO(file_content)
+ upload_file_mock = UploadFile(
+ filename="virus.txt",
+ file=file_obj,
+ headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
+ )
+
+ with patch("backend.api.features.blocks.routes.scan_content_safe") as mock_scan:
+ # Mock virus scan to raise exception
+ mock_scan.side_effect = RuntimeError("Virus detected!")
+
+ upload_file_mock.read = AsyncMock(return_value=file_content)
+
+ with pytest.raises(RuntimeError, match="Virus detected!"):
+ await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ )
+
+
+async def test_upload_file_cloud_storage_failure(test_user_id: str):
+ """Test file upload when cloud storage fails."""
+ file_content = b"test content"
+ file_obj = BytesIO(file_content)
+ upload_file_mock = UploadFile(
+ filename="test.txt",
+ file=file_obj,
+ headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
+ )
+
+ with (
+ patch("backend.api.features.blocks.routes.scan_content_safe") as mock_scan,
+ patch(
+ "backend.api.features.blocks.routes.get_cloud_storage_handler"
+ ) as mock_handler_getter,
+ ):
+ mock_scan.return_value = None
+ mock_handler = AsyncMock()
+ mock_handler.store_file.side_effect = RuntimeError("Storage error!")
+ mock_handler_getter.return_value = mock_handler
+
+ upload_file_mock.read = AsyncMock(return_value=file_content)
+
+ with pytest.raises(RuntimeError, match="Storage error!"):
+ await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ )
+
+
+async def test_upload_file_size_limit_exceeded(test_user_id: str):
+ """Test file upload when file size exceeds the limit."""
+ # Create a file that exceeds the default 256MB limit
+ large_file_content = b"x" * (257 * 1024 * 1024) # 257MB
+ file_obj = BytesIO(large_file_content)
+ upload_file_mock = UploadFile(
+ filename="large_file.txt",
+ file=file_obj,
+ headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
+ )
+
+ upload_file_mock.read = AsyncMock(return_value=large_file_content)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ )
+
+ assert exc_info.value.status_code == 400
+ assert "exceeds the maximum allowed size of 256MB" in exc_info.value.detail
+
+
+async def test_upload_file_gcs_not_configured_fallback(test_user_id: str):
+ """Test file upload fallback to base64 when GCS is not configured."""
+ file_content = b"test file content"
+ file_obj = BytesIO(file_content)
+ upload_file_mock = UploadFile(
+ filename="test.txt",
+ file=file_obj,
+ headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
+ )
+
+ with (
+ patch("backend.api.features.blocks.routes.scan_content_safe") as mock_scan,
+ patch(
+ "backend.api.features.blocks.routes.get_cloud_storage_handler"
+ ) as mock_handler_getter,
+ ):
+ mock_scan.return_value = None
+ mock_handler = AsyncMock()
+ mock_handler.config.gcs_bucket_name = "" # Simulate no GCS bucket configured
+ mock_handler_getter.return_value = mock_handler
+
+ upload_file_mock.read = AsyncMock(return_value=file_content)
+
+ result = await upload_file(
+ file=upload_file_mock,
+ user_id=test_user_id,
+ ctx=_test_ctx(test_user_id),
+ )
+
+ # Verify fallback behavior
+ assert result.file_name == "test.txt"
+ assert result.size == len(file_content)
+ assert result.content_type == "text/plain"
+ assert result.expires_in_hours == 24
+
+ # Verify file_uri is base64 data URI
+ expected_data_uri = "data:text/plain;base64,dGVzdCBmaWxlIGNvbnRlbnQ="
+ assert result.file_uri == expected_data_uri
+
+ # Verify virus scan was called
+ mock_scan.assert_called_once_with(file_content, filename="test.txt")
+
+ # Verify cloud storage methods were NOT called
+ mock_handler.store_file.assert_not_called()
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 2454e4707b..2151479246 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -1,40 +1,15 @@
import asyncio
-import base64
import logging
-import time
-from collections import defaultdict
from datetime import datetime, timezone
from typing import Annotated, get_args
import pydantic
-from autogpt_libs.auth import get_request_context, get_user_id, requires_user
+from autogpt_libs.auth import get_user_id, requires_user
from autogpt_libs.auth.jwt_utils import get_jwt_payload
-from autogpt_libs.auth.models import RequestContext
-from fastapi import (
- APIRouter,
- Body,
- Depends,
- File,
- HTTPException,
- Query,
- Response,
- Security,
- UploadFile,
-)
-from fastapi.concurrency import run_in_threadpool
+from fastapi import APIRouter, Body, HTTPException, Query, Response, Security
from prisma.enums import BriefingFrequency
-from pydantic import BaseModel
-from starlette.status import HTTP_402_PAYMENT_REQUIRED
-from backend.api.model import (
- TimezoneResponse,
- UpdateTimezoneRequest,
- UploadFileResponse,
-)
-from backend.blocks import get_block, get_blocks
-from backend.copilot.rate_limit import enforce_payment_paywall
-from backend.data.block import BlockInput, CompletedBlockOutput
-from backend.data.execution import ExecutionContext
+from backend.api.model import TimezoneResponse, UpdateTimezoneRequest
from backend.data.model import UserOnboarding
from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
from backend.data.onboarding import (
@@ -56,34 +31,16 @@ from backend.data.understanding import (
from backend.data.user import (
get_or_create_user,
get_or_create_user_with_status,
- get_user_by_id,
get_user_notification_preference,
update_user_email,
update_user_notification_preference,
update_user_timezone,
verify_preference_token,
)
-from backend.executor import utils as execution_utils
-from backend.monitoring.instrumentation import record_block_execution
-from backend.util.cache import cached
-from backend.util.cloud_storage import get_cloud_storage_handler
-from backend.util.exceptions import InsufficientBalanceError
-from backend.util.json import dumps
from backend.util.settings import Settings
-from backend.util.timezone_utils import get_user_timezone_or_utc
-from backend.util.virus_scanner import scan_content_safe
from .store.model import StoreAgentDetails
-
-def _create_file_size_error(size_bytes: int, max_size_mb: int) -> HTTPException:
- """Create standardized file size error response."""
- return HTTPException(
- status_code=400,
- detail=f"File size ({size_bytes} bytes) exceeds the maximum allowed size of {max_size_mb}MB",
- )
-
-
settings = Settings()
logger = logging.getLogger(__name__)
@@ -391,224 +348,3 @@ async def submit_onboarding_profile(
await upsert_business_understanding(user_id, understanding_input)
return {"status": "ok"}
-
-
-########################################################
-##################### Blocks ###########################
-########################################################
-
-
-def _compute_blocks_sync() -> str:
- """
- Synchronous function to compute blocks data.
- This does the heavy lifting: instantiate 226+ blocks, compute costs, serialize.
- """
- from backend.data.credit import get_block_cost
-
- block_classes = get_blocks()
- result = []
-
- for block_class in block_classes.values():
- block_instance = block_class()
- if not block_instance.disabled:
- costs = get_block_cost(block_instance)
- # Convert BlockCost BaseModel objects to dictionaries for JSON serialization
- costs_dict = [
- cost.model_dump() if isinstance(cost, BaseModel) else cost
- for cost in costs
- ]
- result.append({**block_instance.to_dict(), "costs": costs_dict})
-
- # Use our JSON utility which properly handles complex types through to_dict conversion
- return dumps(result)
-
-
-@cached(ttl_seconds=3600)
-async def _get_cached_blocks() -> str:
- """
- Async cached function with thundering herd protection.
- On cache miss: runs heavy work in thread pool
- On cache hit: returns cached string immediately (no thread pool needed)
- """
- # Only run in thread pool on cache miss - cache hits return immediately
- return await run_in_threadpool(_compute_blocks_sync)
-
-
-@v1_router.get(
- path="/blocks",
- summary="List available blocks",
- tags=["blocks"],
- dependencies=[Security(requires_user)],
- responses={
- 200: {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {"additionalProperties": True, "type": "object"},
- "type": "array",
- "title": "Response Getv1List Available Blocks",
- }
- }
- },
- }
- },
-)
-async def get_graph_blocks() -> Response:
- # Cache hit: returns immediately, Cache miss: runs in thread pool
- content = await _get_cached_blocks()
- return Response(
- content=content,
- media_type="application/json",
- )
-
-
-@v1_router.post(
- path="/blocks/{block_id}/execute",
- summary="Execute graph block",
- tags=["blocks"],
- dependencies=[Security(requires_user), Depends(enforce_payment_paywall)],
- responses={
- 402: {"description": "Subscription required (NO_TIER user, paywall on)"},
- },
-)
-async def execute_graph_block(
- block_id: str,
- data: BlockInput,
- user_id: Annotated[str, Security(get_user_id)],
- ctx: Annotated[RequestContext, Security(get_request_context)],
-) -> CompletedBlockOutput:
- obj = get_block(block_id)
- if not obj:
- raise HTTPException(status_code=404, detail=f"Block #{block_id} not found.")
- if obj.disabled:
- raise HTTPException(status_code=403, detail=f"Block #{block_id} is disabled.")
-
- user = await get_user_by_id(user_id)
- if not user:
- raise HTTPException(status_code=404, detail="User not found.")
-
- try:
- await execution_utils.charge_for_direct_block_execution(
- user_id=user_id, block=obj, input_data=data, source="internal"
- )
- except InsufficientBalanceError as e:
- raise HTTPException(status_code=HTTP_402_PAYMENT_REQUIRED, detail=str(e)) from e
-
- # Direct block execution has no graph; build a minimal ExecutionContext
- # carrying the caller's identity + timezone so blocks that depend on
- # those (e.g. time blocks) get correct data.
- execution_context = ExecutionContext(
- user_id=user_id,
- user_timezone=get_user_timezone_or_utc(user.timezone),
- )
-
- start_time = time.time()
- try:
- output = defaultdict(list)
- async for name, data in obj.execute(
- data,
- user_id=user_id,
- execution_context=execution_context,
- ):
- output[name].append(data)
-
- # Record successful block execution with duration
- duration = time.time() - start_time
- block_type = obj.__class__.__name__
- record_block_execution(
- block_type=block_type, status="success", duration=duration
- )
-
- return output
- except Exception:
- # Record failed block execution
- duration = time.time() - start_time
- block_type = obj.__class__.__name__
- record_block_execution(block_type=block_type, status="error", duration=duration)
- raise
-
-
-@v1_router.post(
- path="/files/upload",
- summary="Upload file to cloud storage",
- tags=["files"],
- dependencies=[Security(requires_user)],
-)
-async def upload_file(
- user_id: Annotated[str, Security(get_user_id)],
- ctx: Annotated[RequestContext, Security(get_request_context)],
- file: UploadFile = File(...),
- expiration_hours: int = 24,
-) -> UploadFileResponse:
- """
- Upload a file to cloud storage and return a storage key that can be used
- with FileStoreBlock and AgentFileInputBlock.
-
- Args:
- file: The file to upload
- user_id: The user ID
- provider: Cloud storage provider ("gcs", "s3", "azure")
- expiration_hours: Hours until file expires (1-48)
-
- Returns:
- Dict containing the cloud storage path and signed URL
- """
- if expiration_hours < 1 or expiration_hours > 48:
- raise HTTPException(
- status_code=400, detail="Expiration hours must be between 1 and 48"
- )
-
- # Check file size limit before reading content to avoid memory issues
- max_size_mb = settings.config.upload_file_size_limit_mb
- max_size_bytes = max_size_mb * 1024 * 1024
-
- # Try to get file size from headers first
- if hasattr(file, "size") and file.size is not None and file.size > max_size_bytes:
- raise _create_file_size_error(file.size, max_size_mb)
-
- # Read file content
- content = await file.read()
- content_size = len(content)
-
- # Double-check file size after reading (in case header was missing/incorrect)
- if content_size > max_size_bytes:
- raise _create_file_size_error(content_size, max_size_mb)
-
- # Extract common variables
- file_name = file.filename or "uploaded_file"
- content_type = file.content_type or "application/octet-stream"
-
- # Virus scan the content
- await scan_content_safe(content, filename=file_name)
-
- # Check if cloud storage is configured
- cloud_storage = await get_cloud_storage_handler()
- if not cloud_storage.config.gcs_bucket_name:
- # Fallback to base64 data URI when GCS is not configured
- base64_content = base64.b64encode(content).decode("utf-8")
- data_uri = f"data:{content_type};base64,{base64_content}"
-
- return UploadFileResponse(
- file_uri=data_uri,
- file_name=file_name,
- size=content_size,
- content_type=content_type,
- expires_in_hours=expiration_hours,
- )
-
- # Store in cloud storage
- storage_path = await cloud_storage.store_file(
- content=content,
- filename=file_name,
- expiration_hours=expiration_hours,
- user_id=user_id,
- )
-
- return UploadFileResponse(
- file_uri=storage_path,
- file_name=file_name,
- size=content_size,
- content_type=content_type,
- expires_in_hours=expiration_hours,
- )
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index 353cd7c273..bf35487652 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -1,22 +1,19 @@
import json
from datetime import datetime, timezone
-from io import BytesIO
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import Mock
import fastapi
import fastapi.testclient
import pytest
import pytest_mock
-import starlette.datastructures
from autogpt_libs.auth.models import RequestContext
-from fastapi import HTTPException, UploadFile
from pytest_snapshot.plugin import Snapshot
from backend.api.rest_api import handle_internal_http_error
from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError
-from backend.util.exceptions import ConflictError, InsufficientBalanceError
+from backend.util.exceptions import ConflictError
-from .v1 import upload_file, v1_router
+from .v1 import v1_router
def _test_ctx(user_id: str) -> RequestContext:
@@ -166,271 +163,6 @@ def test_update_user_email_route(
)
-# Blocks endpoints tests
-def test_get_graph_blocks(
- mocker: pytest_mock.MockFixture,
- snapshot: Snapshot,
-) -> None:
- """Test get blocks endpoint"""
- # Mock block
- mock_block = Mock()
- mock_block.to_dict.return_value = {
- "id": "test-block",
- "name": "Test Block",
- "description": "A test block",
- "disabled": False,
- }
- mock_block.id = "test-block"
- mock_block.disabled = False
-
- # Mock get_blocks
- mocker.patch(
- "backend.api.features.v1.get_blocks",
- return_value={"test-block": lambda: mock_block},
- )
-
- # Mock block costs
- mocker.patch(
- "backend.data.credit.get_block_cost",
- return_value=[{"cost": 10, "type": "credit"}],
- )
-
- response = client.get("/blocks")
-
- assert response.status_code == 200
- response_data = response.json()
- assert len(response_data) == 1
- assert response_data[0]["id"] == "test-block"
-
- snapshot.snapshot_dir = "snapshots"
- snapshot.assert_match(
- json.dumps(response_data, indent=2, sort_keys=True),
- "blks_all",
- )
-
-
-def test_execute_graph_block(
- mocker: pytest_mock.MockFixture,
- snapshot: Snapshot,
-) -> None:
- """Test execute block endpoint"""
- # Mock block
- mock_block = Mock()
- mock_block.disabled = False
- mock_block.name = "TestBlock"
-
- async def mock_execute(*args, **kwargs):
- yield "output1", {"data": "result1"}
- yield "output2", {"data": "result2"}
-
- mock_block.execute = mock_execute
-
- mocker.patch(
- "backend.api.features.v1.get_block",
- return_value=mock_block,
- )
-
- # Mock user for user_context
- mock_user = Mock()
- mock_user.timezone = "UTC"
-
- mocker.patch(
- "backend.api.features.v1.get_user_by_id",
- return_value=mock_user,
- )
-
- # Default to free block: cost = 0, no charge call. The credit model is
- # patched where the charge would actually go through — the sibling
- # charging test below patches the same target — so "not awaited" is a
- # claim about the code path rather than about an unrelated mock.
- cost_mock = mocker.patch(
- "backend.api.features.v1.execution_utils.block_usage_cost",
- return_value=(0, {}),
- )
- mock_credit_model = mocker.AsyncMock()
- mocker.patch(
- "backend.executor.utils.get_user_credit_model",
- return_value=mock_credit_model,
- )
- request_data = {
- "input_name": "test_input",
- "input_value": "test_value",
- }
-
- response = client.post("/blocks/test-block/execute", json=request_data)
-
- assert response.status_code == 200
- response_data = response.json()
-
- # Cost = 0 path: no spend_credits call.
- cost_mock.assert_called_once()
- mock_credit_model.spend_credits.assert_not_awaited()
-
- snapshot.snapshot_dir = "snapshots"
- snapshot.assert_match(
- json.dumps(response_data, indent=2, sort_keys=True),
- "blks_exec",
- )
-
-
-def test_execute_graph_block_forwards_execution_context(
- mocker: pytest_mock.MockFixture,
- test_user_id: str,
-) -> None:
- """Regression for #12648: blocks that read execution_context (e.g. time
- blocks) crashed because the direct-block-execute route didn't forward
- one. The route must construct an ExecutionContext carrying the caller's
- user_id + timezone and pass it through to ``Block.execute``."""
- captured_kwargs: dict = {}
-
- mock_block = Mock()
- mock_block.disabled = False
- mock_block.name = "TestBlock"
-
- async def mock_execute(*args, **kwargs):
- captured_kwargs.update(kwargs)
- yield "output", {"data": "ok"}
-
- mock_block.execute = mock_execute
-
- mocker.patch(
- "backend.api.features.v1.get_block",
- return_value=mock_block,
- )
-
- mock_user = Mock()
- mock_user.timezone = "America/New_York"
- mocker.patch(
- "backend.api.features.v1.get_user_by_id",
- return_value=mock_user,
- )
-
- mocker.patch(
- "backend.api.features.v1.execution_utils.block_usage_cost",
- return_value=(0, {}),
- )
-
- response = client.post("/blocks/test-block/execute", json={"x": "y"})
-
- assert response.status_code == 200
- assert "execution_context" in captured_kwargs
- ctx = captured_kwargs["execution_context"]
- assert ctx.user_id == test_user_id
- assert ctx.user_timezone == "America/New_York"
-
-
-def test_execute_graph_block_charges_when_cost_positive(
- mocker: pytest_mock.MockFixture,
-) -> None:
- """Paid blocks must charge credits before executing."""
- mock_block = Mock()
- mock_block.disabled = False
- mock_block.id = "paid-block"
- mock_block.name = "PaidBlock"
-
- async def mock_execute(*args, **kwargs):
- yield "output", {"data": "ok"}
-
- mock_block.execute = mock_execute
-
- mocker.patch(
- "backend.api.features.v1.get_block",
- return_value=mock_block,
- )
- mock_user = Mock()
- mock_user.timezone = "UTC"
- mocker.patch(
- "backend.api.features.v1.get_user_by_id",
- return_value=mock_user,
- )
-
- cost_filter = {"model": "gpt-4"}
- mocker.patch(
- "backend.executor.utils.block_usage_cost",
- return_value=(42, cost_filter),
- )
- mock_credit_model = mocker.AsyncMock()
- mocker.patch(
- "backend.executor.utils.get_user_credit_model",
- return_value=mock_credit_model,
- )
-
- response = client.post(
- "/blocks/paid-block/execute", json={"input_name": "x", "input_value": "y"}
- )
-
- assert response.status_code == 200
- mock_credit_model.spend_credits.assert_awaited_once()
- call_kwargs = mock_credit_model.spend_credits.await_args.kwargs
- assert call_kwargs["cost"] == 42
- metadata = call_kwargs["metadata"]
- assert metadata.block_id == "paid-block"
- assert metadata.block == "PaidBlock"
- assert metadata.input == cost_filter
- assert metadata.reason == "Direct internal block execution of PaidBlock"
-
-
-def test_execute_graph_block_returns_402_on_insufficient_balance(
- mocker: pytest_mock.MockFixture,
- test_user_id: str,
-) -> None:
- """If spend_credits raises InsufficientBalanceError, endpoint returns 402."""
- mock_block = Mock()
- mock_block.disabled = False
- mock_block.id = "paid-block"
- mock_block.name = "PaidBlock"
- mock_block.execute = AsyncMock()
-
- mocker.patch(
- "backend.api.features.v1.get_block",
- return_value=mock_block,
- )
- mock_user = Mock()
- mock_user.timezone = "UTC"
- mocker.patch(
- "backend.api.features.v1.get_user_by_id",
- return_value=mock_user,
- )
- mocker.patch(
- "backend.executor.utils.block_usage_cost",
- return_value=(99, {}),
- )
-
- mock_credit_model = mocker.AsyncMock()
- mock_credit_model.spend_credits.side_effect = InsufficientBalanceError(
- message="Insufficient balance",
- user_id=test_user_id,
- balance=10,
- amount=99,
- )
- mocker.patch(
- "backend.executor.utils.get_user_credit_model",
- return_value=mock_credit_model,
- )
-
- response = client.post(
- "/blocks/paid-block/execute", json={"input_name": "x", "input_value": "y"}
- )
-
- assert response.status_code == 402
- mock_block.execute.assert_not_called()
-
-
-def test_execute_graph_block_not_found(
- mocker: pytest_mock.MockFixture,
-) -> None:
- """Test execute block with non-existent block"""
- mocker.patch(
- "backend.api.features.v1.get_block",
- return_value=None,
- )
-
- response = client.post("/blocks/nonexistent-block/execute", json={})
-
- assert response.status_code == 404
- assert "not found" in response.json()["detail"]
-
-
# Invalid request tests
def test_invalid_json_request() -> None:
"""Test endpoint with invalid JSON"""
@@ -440,257 +172,3 @@ def test_invalid_json_request() -> None:
headers={"Content-Type": "application/json"},
)
assert response.status_code == 422
-
-
-async def test_upload_file_success(test_user_id: str):
- """Test successful file upload."""
- # Create mock upload file
- file_content = b"test file content"
- file_obj = BytesIO(file_content)
- upload_file_mock = UploadFile(
- filename="test.txt",
- file=file_obj,
- headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
- )
-
- # Mock dependencies
- with (
- patch("backend.api.features.v1.scan_content_safe") as mock_scan,
- patch(
- "backend.api.features.v1.get_cloud_storage_handler"
- ) as mock_handler_getter,
- ):
- mock_scan.return_value = None
- mock_handler = AsyncMock()
- mock_handler.store_file.return_value = "gcs://test-bucket/uploads/123/test.txt"
- mock_handler_getter.return_value = mock_handler
-
- # Mock file.read()
- upload_file_mock.read = AsyncMock(return_value=file_content)
-
- result = await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- expiration_hours=24,
- )
-
- # Verify result
- assert result.file_uri == "gcs://test-bucket/uploads/123/test.txt"
- assert result.file_name == "test.txt"
- assert result.size == len(file_content)
- assert result.content_type == "text/plain"
- assert result.expires_in_hours == 24
-
- # Verify virus scan was called
- mock_scan.assert_called_once_with(file_content, filename="test.txt")
-
- # Verify cloud storage operations
- mock_handler.store_file.assert_called_once_with(
- content=file_content,
- filename="test.txt",
- expiration_hours=24,
- user_id=test_user_id,
- )
-
-
-async def test_upload_file_no_filename(test_user_id: str):
- """Test file upload without filename."""
- file_content = b"test content"
- file_obj = BytesIO(file_content)
- upload_file_mock = UploadFile(
- filename=None,
- file=file_obj,
- headers=starlette.datastructures.Headers(
- {"content-type": "application/octet-stream"}
- ),
- )
-
- with (
- patch("backend.api.features.v1.scan_content_safe") as mock_scan,
- patch(
- "backend.api.features.v1.get_cloud_storage_handler"
- ) as mock_handler_getter,
- ):
- mock_scan.return_value = None
- mock_handler = AsyncMock()
- mock_handler.store_file.return_value = (
- "gcs://test-bucket/uploads/123/uploaded_file"
- )
- mock_handler_getter.return_value = mock_handler
-
- upload_file_mock.read = AsyncMock(return_value=file_content)
-
- result = await upload_file(
- file=upload_file_mock, user_id=test_user_id, ctx=_test_ctx(test_user_id)
- )
-
- assert result.file_name == "uploaded_file"
- assert result.content_type == "application/octet-stream"
-
- # Verify virus scan was called with default filename
- mock_scan.assert_called_once_with(file_content, filename="uploaded_file")
-
-
-async def test_upload_file_invalid_expiration(test_user_id: str):
- """Test file upload with invalid expiration hours."""
- file_obj = BytesIO(b"content")
- upload_file_mock = UploadFile(
- filename="test.txt",
- file=file_obj,
- headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
- )
-
- # Test expiration too short
- with pytest.raises(HTTPException) as exc_info:
- await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- expiration_hours=0,
- )
- assert exc_info.value.status_code == 400
- assert "between 1 and 48" in exc_info.value.detail
-
- # Test expiration too long
- with pytest.raises(HTTPException) as exc_info:
- await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- expiration_hours=49,
- )
- assert exc_info.value.status_code == 400
- assert "between 1 and 48" in exc_info.value.detail
-
-
-async def test_upload_file_virus_scan_failure(test_user_id: str):
- """Test file upload when virus scan fails."""
- file_content = b"malicious content"
- file_obj = BytesIO(file_content)
- upload_file_mock = UploadFile(
- filename="virus.txt",
- file=file_obj,
- headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
- )
-
- with patch("backend.api.features.v1.scan_content_safe") as mock_scan:
- # Mock virus scan to raise exception
- mock_scan.side_effect = RuntimeError("Virus detected!")
-
- upload_file_mock.read = AsyncMock(return_value=file_content)
-
- with pytest.raises(RuntimeError, match="Virus detected!"):
- await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- )
-
-
-async def test_upload_file_cloud_storage_failure(test_user_id: str):
- """Test file upload when cloud storage fails."""
- file_content = b"test content"
- file_obj = BytesIO(file_content)
- upload_file_mock = UploadFile(
- filename="test.txt",
- file=file_obj,
- headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
- )
-
- with (
- patch("backend.api.features.v1.scan_content_safe") as mock_scan,
- patch(
- "backend.api.features.v1.get_cloud_storage_handler"
- ) as mock_handler_getter,
- ):
- mock_scan.return_value = None
- mock_handler = AsyncMock()
- mock_handler.store_file.side_effect = RuntimeError("Storage error!")
- mock_handler_getter.return_value = mock_handler
-
- upload_file_mock.read = AsyncMock(return_value=file_content)
-
- with pytest.raises(RuntimeError, match="Storage error!"):
- await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- )
-
-
-async def test_upload_file_size_limit_exceeded(test_user_id: str):
- """Test file upload when file size exceeds the limit."""
- # Create a file that exceeds the default 256MB limit
- large_file_content = b"x" * (257 * 1024 * 1024) # 257MB
- file_obj = BytesIO(large_file_content)
- upload_file_mock = UploadFile(
- filename="large_file.txt",
- file=file_obj,
- headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
- )
-
- upload_file_mock.read = AsyncMock(return_value=large_file_content)
-
- with pytest.raises(HTTPException) as exc_info:
- await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- )
-
- assert exc_info.value.status_code == 400
- assert "exceeds the maximum allowed size of 256MB" in exc_info.value.detail
-
-
-async def test_upload_file_gcs_not_configured_fallback(test_user_id: str):
- """Test file upload fallback to base64 when GCS is not configured."""
- file_content = b"test file content"
- file_obj = BytesIO(file_content)
- upload_file_mock = UploadFile(
- filename="test.txt",
- file=file_obj,
- headers=starlette.datastructures.Headers({"content-type": "text/plain"}),
- )
-
- with (
- patch("backend.api.features.v1.scan_content_safe") as mock_scan,
- patch(
- "backend.api.features.v1.get_cloud_storage_handler"
- ) as mock_handler_getter,
- ):
- mock_scan.return_value = None
- mock_handler = AsyncMock()
- mock_handler.config.gcs_bucket_name = "" # Simulate no GCS bucket configured
- mock_handler_getter.return_value = mock_handler
-
- upload_file_mock.read = AsyncMock(return_value=file_content)
-
- result = await upload_file(
- file=upload_file_mock,
- user_id=test_user_id,
- ctx=_test_ctx(test_user_id),
- )
-
- # Verify fallback behavior
- assert result.file_name == "test.txt"
- assert result.size == len(file_content)
- assert result.content_type == "text/plain"
- assert result.expires_in_hours == 24
-
- # Verify file_uri is base64 data URI
- expected_data_uri = "data:text/plain;base64,dGVzdCBmaWxlIGNvbnRlbnQ="
- assert result.file_uri == expected_data_uri
-
- # Verify virus scan was called
- mock_scan.assert_called_once_with(file_content, filename="test.txt")
-
- # Verify cloud storage methods were NOT called
- mock_handler.store_file.assert_not_called()
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 398c49dd36..64dda20736 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -32,6 +32,7 @@ import backend.api.features.api_keys.routes as api_keys_routes
import backend.api.features.auth_email.routes as auth_email_routes
import backend.api.features.billing.credits.routes as credits_routes
import backend.api.features.billing.subscriptions.routes as subscriptions_routes
+import backend.api.features.blocks.routes as blocks_routes
import backend.api.features.briefings.routes
import backend.api.features.builder
import backend.api.features.builder.routes
@@ -431,6 +432,11 @@ app.include_router(
tags=["v1", "credits"],
prefix="/api",
)
+app.include_router(
+ blocks_routes.router,
+ tags=["v1"],
+ prefix="/api",
+)
app.include_router(
auth_email_routes.auth_email_router,
prefix="/api/auth/email",
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 844bfd382d..f9093fae72 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -7578,7 +7578,7 @@
"post": {
"tags": ["v1", "files"],
"summary": "Upload file to cloud storage",
- "description": "Upload a file to cloud storage and return a storage key that can be used\nwith FileStoreBlock and AgentFileInputBlock.\n\nArgs:\n file: The file to upload\n user_id: The user ID\n provider: Cloud storage provider (\"gcs\", \"s3\", \"azure\")\n expiration_hours: Hours until file expires (1-48)\n\nReturns:\n Dict containing the cloud storage path and signed URL",
+ "description": "Upload a file to cloud storage and return a storage key that can be used\nwith FileStoreBlock and AgentFileInputBlock.\n\nArgs:\n file: The file to upload\n user_id: The user ID\n expiration_hours: Hours until file expires (1-48)\n\nReturns:\n Dict containing the cloud storage path and signed URL",
"operationId": "postV1Upload file to cloud storage",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [