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 credit ledger routes into features/billing/credits (#14476)
Reinier van der Leercd364251dc29
diff --git a/autogpt_platform/backend/backend/api/features/billing/__init__.py b/autogpt_platform/backend/backend/api/features/billing/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/billing/credits/__init__.py b/autogpt_platform/backend/backend/api/features/billing/credits/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/billing/credits/routes.py b/autogpt_platform/backend/backend/api/features/billing/credits/routes.pynew file mode 100644index 0000000000..92581b9e6a--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/billing/credits/routes.py@@ -0,0 +1,233 @@+from datetime import datetime+from typing import Annotated++from autogpt_libs.auth import (+ get_request_context,+ get_user_id,+ requires_org_permission,+ requires_user,+)+from autogpt_libs.auth.models import RequestContext+from autogpt_libs.auth.permissions import OrgAction+from fastapi import APIRouter, Header, HTTPException, Query, Response, Security++from backend.api.model import RequestTopUp+from backend.data.credit import (+ AutoTopUpConfig,+ InvoiceListItem,+ RefundRequest,+ TransactionHistory,+ get_auto_top_up,+ get_credit_model,+ set_auto_top_up,+)++# All nine routes carry tags=["credits"] and only Security(requires_user), so+# both live at the mount and the router rather than on each route.+router = APIRouter(dependencies=[Security(requires_user)])+++# MANAGE_BILLING excludes org admins by design; personal-org membership rows+# are always isOwner=True, so this gate is a no-op for personal orgs.+#+# Release ordering (SECRT-2449): the frontend never sends X-Org-Id, so the gate+# is inert today. Forwarding it must not ship before the billing UI handles 403+# for plain members — they would otherwise lose the nav Wallet (GET /credits)+# and the settings billing page (/credits/transactions, /credits/refunds,+# /credits/invoices).+BillingManagerContext = Annotated[+ RequestContext,+ Security(requires_org_permission(OrgAction.MANAGE_BILLING)),+]+++ path="/credits",+ summary="Get user credits",+)+async def get_user_credits(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+) -> dict[str, int]:+ credit_model = await get_credit_model(user_id, ctx.org_id)+ return {"credits": await credit_model.get_credits(user_id)}+++ path="/credits",+ summary="Request credit top up",+)+async def request_top_up(+ request: RequestTopUp,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+ x_datafast_visitor_id: Annotated[+ str | None, Header(include_in_schema=False)+ ] = None,+ x_datafast_session_id: Annotated[+ str | None, Header(include_in_schema=False)+ ] = None,+):+ credit_model = await get_credit_model(user_id, ctx.org_id)+ checkout_url = await credit_model.top_up_intent(+ user_id,+ request.credit_amount,+ datafast_visitor_id=x_datafast_visitor_id,+ datafast_session_id=x_datafast_session_id,+ )+ return {"checkout_url": checkout_url}+++ path="/credits/{transaction_key}/refund",+ summary="Refund credit transaction",+)+async def refund_top_up(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+ transaction_key: str,+ metadata: dict[str, str],+) -> int:+ credit_model = await get_credit_model(user_id, ctx.org_id)+ return await credit_model.top_up_refund(user_id, transaction_key, metadata)+++ path="/credits",+ summary="Fulfill checkout session",+)+async def fulfill_checkout(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+):+ credit_model = await get_credit_model(user_id, ctx.org_id)+ await credit_model.fulfill_checkout(user_id=user_id)+ return Response(status_code=200)+++ path="/credits/auto-top-up",+ summary="Configure auto top up",+)+async def configure_user_auto_top_up(+ request: AutoTopUpConfig,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+) -> str:+ """Configure auto top-up settings and perform an immediate top-up if needed.++ Raises HTTPException(422) if the request parameters are invalid or if+ the credit top-up fails.+ """+ if request.threshold < 0:+ raise HTTPException(status_code=422, detail="Threshold must be greater than 0")+ if request.amount < 500 and request.amount != 0:+ raise HTTPException(+ status_code=422, detail="Amount must be greater than or equal to 500"+ )+ if request.amount != 0 and request.amount < request.threshold:+ raise HTTPException(+ status_code=422, detail="Amount must be greater than or equal to threshold"+ )++ credit_model = await get_credit_model(user_id, ctx.org_id)+ current_balance = await credit_model.get_credits(user_id)++ try:+ if current_balance < request.threshold:+ await credit_model.top_up_credits(user_id, request.amount)+ else:+ await credit_model.top_up_credits(user_id, 0)+ except NotImplementedError as e:+ raise HTTPException(+ status_code=501, detail="Auto top-up is not available in this context"+ ) from e+ except ValueError as e:+ known_messages = (+ "must not be negative",+ "already exists for user",+ "No payment method found",+ )+ if any(msg in str(e) for msg in known_messages):+ raise HTTPException(status_code=422, detail=str(e))+ raise++ try:+ await set_auto_top_up(+ user_id, AutoTopUpConfig(threshold=request.threshold, amount=request.amount)+ )+ except ValueError as e:+ raise HTTPException(status_code=422, detail=str(e))+ return "Auto top-up settings updated"+++ path="/credits/auto-top-up",+ summary="Get auto top up",+)+async def get_user_auto_top_up(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> AutoTopUpConfig:+ return await get_auto_top_up(user_id)+++ path="/credits/transactions",+ summary="Get credit history",+)+async def get_credit_history(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+ transaction_time: datetime | None = None,+ transaction_type: str | None = None,+ transaction_count_limit: int = 100,+ cursor: str | None = None,+) -> TransactionHistory:+ if transaction_count_limit < 1 or transaction_count_limit > 1000:+ raise ValueError("Transaction count limit must be between 1 and 1000")++ credit_model = await get_credit_model(user_id, ctx.org_id)+ return await credit_model.get_transaction_history(+ user_id=user_id,+ transaction_time_ceiling=transaction_time,+ transaction_count_limit=transaction_count_limit,+ transaction_type=transaction_type,+ cursor=cursor,+ viewer_organization_id=ctx.org_id,+ )+++ path="/credits/refunds",+ summary="Get refund requests",+)+async def get_refund_requests(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+) -> list[RefundRequest]:+ credit_model = await get_credit_model(user_id, ctx.org_id)+ return await credit_model.get_refund_requests(user_id)+++ path="/credits/invoices",+ summary="List Stripe invoices",+)+async def list_invoices(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: BillingManagerContext,+ limit: int = Query(24, ge=1, le=100),+) -> list[InvoiceListItem]:+ """Recent Stripe invoices for the caller's active org, for billing managers.++ The invoices belong to the org the request resolves to (the caller's+ personal org when no ``X-Org-Id`` is supplied), so this is restricted to+ org roles holding ``MANAGE_BILLING``.++ Each item includes ``hosted_invoice_url`` (Stripe-hosted view) and+ ``invoice_pdf_url`` (direct PDF download). Returns an empty list when+ the credit system is disabled or the org has no Stripe customer yet.+ """+ credit_model = await get_credit_model(user_id, ctx.org_id)+ return await credit_model.list_invoices(user_id, limit=limit)diff --git a/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py b/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.pynew file mode 100644index 0000000000..e7703f1bb4--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py@@ -0,0 +1,556 @@+"""Tests for the credit ledger routes."""++import json+from datetime import datetime, timezone+from unittest.mock import ANY, AsyncMock, Mock++import fastapi+import fastapi.testclient+import pytest+import pytest_mock+from autogpt_libs.auth import get_request_context, get_user_id, requires_user+from autogpt_libs.auth.models import RequestContext+from fastapi.routing import APIRoute+from pytest_snapshot.plugin import Snapshot++from backend.api.features.billing.credits.routes import get_credit_history, router+from backend.api.rest_api import app as real_app+from backend.api.rest_api import handle_internal_http_error+from backend.data.credit import AutoTopUpConfig, UserCreditBase+from backend.data.model import TransactionHistory++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"]++ # The real get_request_context queries Prisma to resolve the personal org,+ # which closes the test event loop between sync TestClient calls.+ 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()+++EXPECTED_OPERATIONS = {+ ("get", "/api/credits"),+ ("post", "/api/credits"),+ ("patch", "/api/credits"),+ ("post", "/api/credits/{transaction_key}/refund"),+ ("get", "/api/credits/auto-top-up"),+ ("post", "/api/credits/auto-top-up"),+ ("get", "/api/credits/transactions"),+ ("get", "/api/credits/refunds"),+ ("get", "/api/credits/invoices"),+}++[email protected]("method,path", sorted(EXPECTED_OPERATIONS))+def test_credit_operation_is_published(method: str, path: str):+ operation = real_app.openapi()["paths"][path][method]+ assert operation["tags"] == ["v1", "credits"]+ assert "security" in operation++[email protected]("path", sorted({p for _, p in EXPECTED_OPERATIONS}))+def test_credit_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, so removing the router's requires_user+ leaves the schema unchanged. 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_credit_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.billing.credits.routes"+ for method in route.methods+ if method != "HEAD"+ }+ assert served == EXPECTED_OPERATIONS+++# The subscription and Stripe routes stay in v1 for now and share the /credits+# prefix; /credits/{transaction_key}/refund is the only wildcard among them.+ "path,module",+ [+ ("/api/credits/subscription", "backend.api.features.v1"),+ ("/api/credits/manage", "backend.api.features.v1"),+ ("/api/credits/stripe_webhook", "backend.api.features.v1"),+ ("/api/credits/transactions", "backend.api.features.billing.credits.routes"),+ (+ "/api/credits/{transaction_key}/refund",+ "backend.api.features.billing.credits.routes",+ ),+ ],+)+def test_credit_subpath_is_served_by_the_expected_module(path: str, module: str):+ handlers = {+ route.endpoint.__module__+ for route in real_app.routes+ if isinstance(route, APIRoute) and route.path == path+ }+ assert handlers == {module}+++def test_get_user_credits(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+) -> None:+ """Test get user credits endpoint"""+ mock_credit_model = Mock()+ mock_credit_model.get_credits = AsyncMock(return_value=1000)+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.get("/credits")++ assert response.status_code == 200+ response_data = response.json()+ assert response_data["credits"] == 1000++ snapshot.snapshot_dir = "snapshots"+ snapshot.assert_match(+ json.dumps(response_data, indent=2, sort_keys=True),+ "cred_bal",+ )+++def test_request_top_up(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+) -> None:+ """Test request top up endpoint"""+ mock_credit_model = Mock()+ mock_credit_model.top_up_intent = AsyncMock(+ return_value="https://checkout.example.com/session123"+ )+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ request_data = {"credit_amount": 500}++ response = client.post("/credits", json=request_data)++ assert response.status_code == 200+ response_data = response.json()+ assert "checkout_url" in response_data++ snapshot.snapshot_dir = "snapshots"+ snapshot.assert_match(+ json.dumps(response_data, indent=2, sort_keys=True),+ "cred_topup_req",+ )+++def test_request_top_up_forwards_datafast_headers(+ mocker: pytest_mock.MockFixture,+) -> None:+ """DataFast attribution headers are forwarded to top_up_intent."""+ mock_credit_model = Mock()+ mock_credit_model.top_up_intent = AsyncMock(+ return_value="https://checkout.example.com/session123"+ )+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.post(+ "/credits",+ json={"credit_amount": 500},+ headers={+ "X-Datafast-Visitor-Id": "vis_1",+ "X-Datafast-Session-Id": "ses_1",+ },+ )++ assert response.status_code == 200+ mock_credit_model.top_up_intent.assert_awaited_once_with(+ ANY,+ 500,+ datafast_visitor_id="vis_1",+ datafast_session_id="ses_1",+ )+++def test_get_auto_top_up(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+) -> None:+ """Test get auto top-up configuration endpoint"""+ mock_config = AutoTopUpConfig(threshold=100, amount=500)++ mocker.patch(+ "backend.api.features.billing.credits.routes.get_auto_top_up",+ return_value=mock_config,+ )++ response = client.get("/credits/auto-top-up")++ assert response.status_code == 200+ response_data = response.json()+ assert response_data["threshold"] == 100+ assert response_data["amount"] == 500++ snapshot.snapshot_dir = "snapshots"+ snapshot.assert_match(+ json.dumps(response_data, indent=2, sort_keys=True),+ "cred_topup_cfg",+ )+++def test_configure_auto_top_up(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+) -> None:+ """Test configure auto top-up endpoint - this test would have caught the enum casting bug"""+ # Mock the set_auto_top_up function to avoid database operations+ mocker.patch(+ "backend.api.features.billing.credits.routes.set_auto_top_up",+ return_value=None,+ )++ # Mock credit model to avoid Stripe API calls+ mock_credit_model = mocker.AsyncMock()+ mock_credit_model.get_credits.return_value = 50 # Current balance below threshold+ mock_credit_model.top_up_credits.return_value = None++ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ # Test data+ request_data = {+ "threshold": 100,+ "amount": 500,+ }++ response = client.post("/credits/auto-top-up", json=request_data)++ # This should succeed with our fix, but would have failed before with the enum casting error+ assert response.status_code == 200+ assert response.json() == "Auto top-up settings updated"+++def test_configure_auto_top_up_refuses_when_model_has_no_payment_path(+ mocker: pytest_mock.MockFixture,+) -> None:+ set_auto_top_up = mocker.patch(+ "backend.api.features.billing.credits.routes.set_auto_top_up"+ )++ mock_credit_model = mocker.AsyncMock()+ mock_credit_model.get_credits.return_value = 50+ mock_credit_model.top_up_credits.side_effect = NotImplementedError(+ "Org-level Stripe top-up not yet implemented"+ )+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.post(+ "/credits/auto-top-up", json={"threshold": 500, "amount": 500}+ )++ assert response.status_code == 501+ set_auto_top_up.assert_not_called()+++def test_configure_auto_top_up_validation_errors(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Test configure auto top-up endpoint validation"""+ # Mock set_auto_top_up to avoid database operations for successful case+ mocker.patch("backend.api.features.billing.credits.routes.set_auto_top_up")++ # Mock credit model to avoid Stripe API calls for the successful case+ mock_credit_model = mocker.AsyncMock()+ mock_credit_model.get_credits.return_value = 50+ mock_credit_model.top_up_credits.return_value = None++ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ # Test negative threshold+ response = client.post(+ "/credits/auto-top-up", json={"threshold": -1, "amount": 500}+ )+ assert response.status_code == 422 # Validation error++ # Test amount too small (but not 0)+ response = client.post(+ "/credits/auto-top-up", json={"threshold": 100, "amount": 100}+ )+ assert response.status_code == 422 # Validation error++ # Test amount = 0 (should be allowed)+ response = client.post("/credits/auto-top-up", json={"threshold": 100, "amount": 0})+ assert response.status_code == 200 # Should succeed+++def test_list_invoices_returns_mapped_payload(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The /credits/invoices route should return whatever the credit model+ yields, serialised through the InvoiceListItem schema."""+ from backend.data.credit import InvoiceListItem++ invoice = InvoiceListItem(+ id="in_1",+ number="INV-001",+ created_at=datetime(2026, 4, 1, tzinfo=timezone.utc),+ total_cents=2500,+ amount_paid_cents=0,+ currency="usd",+ status="open",+ description="Subscription",+ hosted_invoice_url="https://invoice.stripe.com/i/test",+ invoice_pdf_url="https://invoice.stripe.com/i/test/pdf",+ )++ mock_credit_model = Mock()+ mock_credit_model.list_invoices = AsyncMock(return_value=[invoice])+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.get("/credits/invoices?limit=24")++ assert response.status_code == 200+ payload = response.json()+ assert len(payload) == 1+ row = payload[0]+ assert row["id"] == "in_1"+ assert row["total_cents"] == 2500+ assert row["amount_paid_cents"] == 0+ assert row["status"] == "open"+ assert row["hosted_invoice_url"] == "https://invoice.stripe.com/i/test"+ mock_credit_model.list_invoices.assert_awaited_once()+ # Ensure the limit query param is forwarded.+ assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}+++def test_list_invoices_clamps_limit(mocker: pytest_mock.MockFixture) -> None:+ """FastAPI's Query(le=100) should reject limit > 100."""+ mock_credit_model = Mock()+ mock_credit_model.list_invoices = AsyncMock(return_value=[])+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.get("/credits/invoices?limit=500")++ assert response.status_code == 422 # Validation error+ mock_credit_model.list_invoices.assert_not_awaited()+++def test_list_invoices_default_limit(mocker: pytest_mock.MockFixture) -> None:+ """Omitting ?limit should default to 24."""+ mock_credit_model = Mock()+ mock_credit_model.list_invoices = AsyncMock(return_value=[])+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.get("/credits/invoices")++ assert response.status_code == 200+ assert response.json() == []+ assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}+++def test_refund_top_up_forwards_the_transaction_key_and_metadata(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The key identifies which top-up is being refunded; dropping it would+ refund the wrong transaction."""+ credit_model = Mock()+ credit_model.top_up_refund = AsyncMock(return_value=500)+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )++ response = client.post("/credits/txn-1/refund", json={"reason": "duplicate"})++ assert response.status_code == 200+ args = credit_model.top_up_refund.await_args.args+ assert args[1] == "txn-1"+ assert args[2] == {"reason": "duplicate"}+++def test_fulfill_checkout_credits_the_calling_user(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Fulfilment is keyed on the authenticated user, not on anything in the+ request — that is what stops one account fulfilling another's checkout."""+ credit_model = Mock()+ credit_model.fulfill_checkout = AsyncMock()+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )++ response = client.patch("/credits")++ assert response.status_code == 200+ assert set(credit_model.fulfill_checkout.await_args.kwargs) == {"user_id"}+++def test_get_refund_requests_is_scoped_to_the_caller(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ credit_model = Mock()+ credit_model.get_refund_requests = AsyncMock(return_value=[])+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )++ response = client.get("/credits/refunds")++ assert response.status_code == 200+ assert credit_model.get_refund_requests.await_args.args[0] == test_user_id+++def test_configure_auto_top_up_maps_an_unavailable_backend_to_501(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A context without auto top-up must say so, not surface as a 500."""+ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=0)+ credit_model.top_up_credits = AsyncMock(side_effect=NotImplementedError)+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )++ response = client.post(+ "/credits/auto-top-up", json={"threshold": 1000, "amount": 1000}+ )++ assert response.status_code == 501+++def test_request_top_up_rejects_a_missing_amount() -> None:+ """Moved with its route from v1_test's invalid-request section."""+ response = client.post("/credits", json={})++ assert response.status_code == 422+++# The credit-history route is exercised against its own app: it needs the+# ValueError -> 400 handler the real app installs, which the module-level+# client above does not carry.+HISTORY_CONTEXT = RequestContext(+ user_id="user",+ org_id="org",+ team_id=None,+ is_org_owner=True,+ is_org_admin=False,+ is_org_billing_manager=False,+ is_team_admin=False,+ is_team_billing_manager=False,+ seat_status="ACTIVE",+)+++def history_client():+ history_app = fastapi.FastAPI()+ history_app.include_router(router)+ history_app.add_exception_handler(ValueError, handle_internal_http_error(400))+ history_app.dependency_overrides[requires_user] = lambda: None+ history_app.dependency_overrides[get_user_id] = lambda: "user"+ history_app.dependency_overrides[get_request_context] = lambda: HISTORY_CONTEXT+ return fastapi.testclient.TestClient(history_app)++[email protected]("limit", [0, -1, 1001])+def test_invalid_history_limit_returns_400(history_client, limit):+ response = history_client.get(+ "/credits/transactions", params={"transaction_count_limit": limit}+ )+ assert response.status_code == 400+ assert "Transaction count limit" in response.json()["detail"]+ assert response.json()["message"] == "Failed to process GET /credits/transactions"+++def test_invalid_cursor_returns_400(history_client, monkeypatch):+ model = AsyncMock(spec=UserCreditBase)+ model.get_transaction_history.side_effect = ValueError(+ "Invalid credit history cursor"+ )+ monkeypatch.setattr(+ "backend.api.features.billing.credits.routes.get_credit_model",+ AsyncMock(return_value=model),+ )+ response = history_client.get("/credits/transactions", params={"cursor": "invalid"})+ assert response.status_code == 400+ assert response.json()["detail"] == "Invalid credit history cursor"+ assert response.json()["message"] == "Failed to process GET /credits/transactions"+++async def test_history_route_forwards_cursor_and_org_context(monkeypatch):+ model = AsyncMock(spec=UserCreditBase)+ model.get_transaction_history.return_value = TransactionHistory(+ transactions=[], next_transaction_time=None+ )+ get_model = AsyncMock(return_value=model)+ monkeypatch.setattr(+ "backend.api.features.billing.credits.routes.get_credit_model", get_model+ )+ result = await get_credit_history(+ user_id="user", ctx=HISTORY_CONTEXT, cursor="cursor", transaction_count_limit=50+ )+ get_model.assert_awaited_once_with("user", "org")+ model.get_transaction_history.assert_awaited_once_with(+ user_id="user",+ transaction_time_ceiling=None,+ transaction_count_limit=50,+ transaction_type=None,+ cursor="cursor",+ viewer_organization_id="org",+ )+ assert result.transactions == []diff --git a/autogpt_platform/backend/backend/api/features/credits_rate_limit.py b/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit.pysimilarity index 100%rename from autogpt_platform/backend/backend/api/features/credits_rate_limit.pyrename to autogpt_platform/backend/backend/api/features/billing/credits_rate_limit.pydiff --git a/autogpt_platform/backend/backend/api/features/credits_rate_limit_test.py b/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.pysimilarity index 96%rename from autogpt_platform/backend/backend/api/features/credits_rate_limit_test.pyrename to autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.pyindex acb9814a4a..227f4fadd1 100644--- a/autogpt_platform/backend/backend/api/features/credits_rate_limit_test.py+++ b/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.py@@ -11,7 +11,7 @@ import pytestfrom redis.exceptions import ConnectionError as RedisConnectionErrorfrom redis.exceptions import RedisClusterException, ResponseError-from backend.api.features import credits_rate_limit as rate_limit+from backend.api.features.billing import credits_rate_limit as rate_limitclass FakeRedis:@@ -44,7 +44,7 @@ def fake_redis(mocker):executes the limiter's script semantics."""redis = FakeRedis()mocker.patch(- "backend.api.features.credits_rate_limit.get_redis_async",+ "backend.api.features.billing.credits_rate_limit.get_redis_async",new=AsyncMock(return_value=redis),)return redis@@ -57,7 +57,7 @@ def mock_redis(mocker):redis = MagicMock()redis.eval = AsyncMock()mocker.patch(- "backend.api.features.credits_rate_limit.get_redis_async",+ "backend.api.features.billing.credits_rate_limit.get_redis_async",new=AsyncMock(return_value=redis),)return redis@@ -159,7 +159,7 @@ async def test_fails_open_on_redis_errors_from_the_command(mock_redis, error):async def test_fails_open_when_connect_fails(mocker):"""Trouble reaching Redis at all also fails open."""mocker.patch(- "backend.api.features.credits_rate_limit.get_redis_async",+ "backend.api.features.billing.credits_rate_limit.get_redis_async",new=AsyncMock(side_effect=RedisClusterException("cluster down")),)await rate_limit.enforce_subscription_status_rate_limit("u1")diff --git a/autogpt_platform/backend/backend/api/features/credit_history_routes_test.py b/autogpt_platform/backend/backend/api/features/credit_history_routes_test.pydeleted file mode 100644index 22f7fc92fa..0000000000--- a/autogpt_platform/backend/backend/api/features/credit_history_routes_test.py+++ /dev/null@@ -1,82 +0,0 @@-from unittest.mock import AsyncMock--import pytest-from autogpt_libs.auth import get_request_context, get_user_id, requires_user-from autogpt_libs.auth.models import RequestContext-from fastapi import FastAPI-from fastapi.testclient import TestClient--from backend.api.features.v1 import get_credit_history, v1_router-from backend.api.rest_api import handle_internal_http_error-from backend.data.credit import UserCreditBase-from backend.data.model import TransactionHistory--CONTEXT = RequestContext(- user_id="user",- org_id="org",- team_id=None,- is_org_owner=True,- is_org_admin=False,- is_org_billing_manager=False,- is_team_admin=False,- is_team_billing_manager=False,- seat_status="ACTIVE",-)---def client():- app = FastAPI()- app.include_router(v1_router)- app.add_exception_handler(ValueError, handle_internal_http_error(400))- app.dependency_overrides[requires_user] = lambda: None- app.dependency_overrides[get_user_id] = lambda: "user"- app.dependency_overrides[get_request_context] = lambda: CONTEXT- return TestClient(app)--[email protected]("limit", [0, -1, 1001])-def test_invalid_history_limit_returns_400(client, limit):- response = client.get(- "/credits/transactions", params={"transaction_count_limit": limit}- )- assert response.status_code == 400- assert "Transaction count limit" in response.json()["detail"]- assert response.json()["message"] == "Failed to process GET /credits/transactions"---def test_invalid_cursor_returns_400(client, monkeypatch):- model = AsyncMock(spec=UserCreditBase)- model.get_transaction_history.side_effect = ValueError(- "Invalid credit history cursor"- )- monkeypatch.setattr(- "backend.api.features.v1.get_credit_model", AsyncMock(return_value=model)- )- response = client.get("/credits/transactions", params={"cursor": "invalid"})- assert response.status_code == 400- assert response.json()["detail"] == "Invalid credit history cursor"- assert response.json()["message"] == "Failed to process GET /credits/transactions"---async def test_history_route_forwards_cursor_and_org_context(monkeypatch):- model = AsyncMock(spec=UserCreditBase)- model.get_transaction_history.return_value = TransactionHistory(- transactions=[], next_transaction_time=None- )- get_model = AsyncMock(return_value=model)- monkeypatch.setattr("backend.api.features.v1.get_credit_model", get_model)- result = await get_credit_history(- user_id="user", ctx=CONTEXT, cursor="cursor", transaction_count_limit=50- )- get_model.assert_awaited_once_with("user", "org")- model.get_transaction_history.assert_awaited_once_with(- user_id="user",- transaction_time_ceiling=None,- transaction_count_limit=50,- transaction_type=None,- cursor="cursor",- viewer_organization_id="org",- )- assert result.transactions == []diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.pyindex a8694b7d47..7cf91df004 100644--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py@@ -10,7 +10,7 @@ import stripefrom autogpt_libs.auth.jwt_utils import get_jwt_payloadfrom prisma.enums import SubscriptionTier-from .credits_rate_limit import enforce_subscription_status_rate_limit+from .billing.credits_rate_limit import enforce_subscription_status_rate_limitfrom .v1 import _validate_checkout_redirect_url, v1_routerTEST_USER_ID = "3e53486c-cf57-477e-ba2a-cb02dc828e1a"diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.pyindex 775026be16..63365241bd 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py@@ -6,7 +6,7 @@ from autogpt_libs.auth import get_user_idfrom fastapi import APIRouter, Depends, Header, HTTPException, Securityfrom pydantic import BaseModel, Field-from backend.api.features.credits_rate_limit import (+from backend.api.features.billing.credits_rate_limit import (enforce_subscription_status_rate_limit,)from backend.data.credit import _datafast_metadata, sync_subscription_from_stripediff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex cb645caacc..b1f0220312 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -9,15 +9,9 @@ from urllib.parse import urlparseimport pydanticimport stripe-from autogpt_libs.auth import (- get_request_context,- get_user_id,- requires_org_permission,- requires_user,-)+from autogpt_libs.auth import get_request_context, get_user_id, requires_userfrom autogpt_libs.auth.jwt_utils import get_jwt_payloadfrom autogpt_libs.auth.models import RequestContext-from autogpt_libs.auth.permissions import OrgActionfrom fastapi import (APIRouter,Body,@@ -37,11 +31,10 @@ from pydantic import BaseModel, Fieldfrom starlette.status import HTTP_402_PAYMENT_REQUIREDfrom typing_extensions import Optional-from backend.api.features.credits_rate_limit import (+from backend.api.features.billing.credits_rate_limit import (enforce_subscription_status_rate_limit,)from backend.api.model import (- RequestTopUp,TimezoneResponse,UpdateTimezoneRequest,UploadFileResponse,@@ -50,16 +43,11 @@ from backend.blocks import get_block, get_blocksfrom backend.copilot.rate_limit import enforce_payment_paywall, get_tier_multipliersfrom backend.data.block import BlockInput, CompletedBlockOutputfrom backend.data.credit import (- AutoTopUpConfig,- InvoiceListItem,PendingChangeUnknown,- RefundRequest,- TransactionHistory,UserCredit,cancel_stripe_subscription,create_subscription_checkout,get_active_subscription_period_end,- get_auto_top_up,get_credit_model,get_pending_subscription_change,get_proration_credit_cents,@@ -69,7 +57,6 @@ from backend.data.credit import (handle_subscription_payment_success,modify_stripe_subscription_for_tier,release_pending_subscription_schedule,- set_auto_top_up,set_subscription_tier,sync_subscription_from_stripe,sync_subscription_schedule_from_stripe,@@ -675,163 +662,6 @@ async def upload_file(########################################################-# MANAGE_BILLING excludes org admins by design; personal-org membership rows-# are always isOwner=True, so this gate is a no-op for personal orgs.-#-# Release ordering (SECRT-2449): the frontend never sends X-Org-Id, so the gate-# is inert today. Forwarding it must not ship before the billing UI handles 403-# for plain members — they would otherwise lose the nav Wallet (GET /credits)-# and the settings billing page (/credits/transactions, /credits/refunds,-# /credits/invoices).-BillingManagerContext = Annotated[- RequestContext,- Security(requires_org_permission(OrgAction.MANAGE_BILLING)),-]---@v1_router.get(- path="/credits",- tags=["credits"],- summary="Get user credits",- dependencies=[Security(requires_user)],-)-async def get_user_credits(- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,-) -> dict[str, int]:- credit_model = await get_credit_model(user_id, ctx.org_id)- return {"credits": await credit_model.get_credits(user_id)}---@v1_router.post(- path="/credits",- summary="Request credit top up",- tags=["credits"],- dependencies=[Security(requires_user)],-)-async def request_top_up(- request: RequestTopUp,- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,- x_datafast_visitor_id: Annotated[- str | None, Header(include_in_schema=False)- ] = None,- x_datafast_session_id: Annotated[- str | None, Header(include_in_schema=False)- ] = None,-):- credit_model = await get_credit_model(user_id, ctx.org_id)- checkout_url = await credit_model.top_up_intent(- user_id,- request.credit_amount,- datafast_visitor_id=x_datafast_visitor_id,- datafast_session_id=x_datafast_session_id,- )- return {"checkout_url": checkout_url}---@v1_router.post(- path="/credits/{transaction_key}/refund",- summary="Refund credit transaction",- tags=["credits"],- dependencies=[Security(requires_user)],-)-async def refund_top_up(- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,- transaction_key: str,- metadata: dict[str, str],-) -> int:- credit_model = await get_credit_model(user_id, ctx.org_id)- return await credit_model.top_up_refund(user_id, transaction_key, metadata)---@v1_router.patch(- path="/credits",- summary="Fulfill checkout session",- tags=["credits"],- dependencies=[Security(requires_user)],-)-async def fulfill_checkout(- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,-):- credit_model = await get_credit_model(user_id, ctx.org_id)- await credit_model.fulfill_checkout(user_id=user_id)- return Response(status_code=200)---@v1_router.post(- path="/credits/auto-top-up",- summary="Configure auto top up",- tags=["credits"],- dependencies=[Security(requires_user)],-)-async def configure_user_auto_top_up(- request: AutoTopUpConfig,- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,-) -> str:- """Configure auto top-up settings and perform an immediate top-up if needed.-- Raises HTTPException(422) if the request parameters are invalid or if- the credit top-up fails.- """- if request.threshold < 0:- raise HTTPException(status_code=422, detail="Threshold must be greater than 0")- if request.amount < 500 and request.amount != 0:- raise HTTPException(- status_code=422, detail="Amount must be greater than or equal to 500"- )- if request.amount != 0 and request.amount < request.threshold:- raise HTTPException(- status_code=422, detail="Amount must be greater than or equal to threshold"- )-- credit_model = await get_credit_model(user_id, ctx.org_id)- current_balance = await credit_model.get_credits(user_id)-- try:- if current_balance < request.threshold:- await credit_model.top_up_credits(user_id, request.amount)- else:- await credit_model.top_up_credits(user_id, 0)- except NotImplementedError as e:- raise HTTPException(- status_code=501, detail="Auto top-up is not available in this context"- ) from e- except ValueError as e:- known_messages = (- "must not be negative",- "already exists for user",- "No payment method found",- )- if any(msg in str(e) for msg in known_messages):- raise HTTPException(status_code=422, detail=str(e))- raise-- try:- await set_auto_top_up(- user_id, AutoTopUpConfig(threshold=request.threshold, amount=request.amount)- )- except ValueError as e:- raise HTTPException(status_code=422, detail=str(e))- return "Auto top-up settings updated"---@v1_router.get(- path="/credits/auto-top-up",- summary="Get auto top up",- tags=["credits"],- dependencies=[Security(requires_user)],-)-async def get_user_auto_top_up(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> AutoTopUpConfig:- return await get_auto_top_up(user_id)--class SubscriptionTierRequest(BaseModel):tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]success_url: str = ""@@ -1685,70 +1515,3 @@ async def manage_payment_method() -> dict[str, str]:credit_model = await get_credit_model(user_id, ctx.org_id)return {"url": await credit_model.create_billing_portal_session(user_id)}---@v1_router.get(- path="/credits/transactions",- tags=["credits"],- summary="Get credit history",- dependencies=[Security(requires_user)],-)-async def get_credit_history(- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,- transaction_time: datetime | None = None,- transaction_type: str | None = None,- transaction_count_limit: int = 100,- cursor: str | None = None,-) -> TransactionHistory:- if transaction_count_limit < 1 or transaction_count_limit > 1000:- raise ValueError("Transaction count limit must be between 1 and 1000")-- credit_model = await get_credit_model(user_id, ctx.org_id)- return await credit_model.get_transaction_history(- user_id=user_id,- transaction_time_ceiling=transaction_time,- transaction_count_limit=transaction_count_limit,- transaction_type=transaction_type,- cursor=cursor,- viewer_organization_id=ctx.org_id,- )---@v1_router.get(- path="/credits/refunds",- tags=["credits"],- summary="Get refund requests",- dependencies=[Security(requires_user)],-)-async def get_refund_requests(- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,-) -> list[RefundRequest]:- credit_model = await get_credit_model(user_id, ctx.org_id)- return await credit_model.get_refund_requests(user_id)---@v1_router.get(- path="/credits/invoices",- tags=["credits"],- summary="List Stripe invoices",- dependencies=[Security(requires_user)],-)-async def list_invoices(- user_id: Annotated[str, Security(get_user_id)],- ctx: BillingManagerContext,- limit: int = Query(24, ge=1, le=100),-) -> list[InvoiceListItem]:- """Recent Stripe invoices for the caller's active org, for billing managers.-- The invoices belong to the org the request resolves to (the caller's- personal org when no ``X-Org-Id`` is supplied), so this is restricted to- org roles holding ``MANAGE_BILLING``.-- Each item includes ``hosted_invoice_url`` (Stripe-hosted view) and- ``invoice_pdf_url`` (direct PDF download). Returns an empty list when- the credit system is disabled or the org has no Stripe customer yet.- """- credit_model = await get_credit_model(user_id, ctx.org_id)- return await credit_model.list_invoices(user_id, limit=limit)diff --git a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.pyindex c0e4528143..8669817036 100644--- a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py@@ -39,10 +39,14 @@ from backend.api.rest_api import app as real_appfrom backend.data.model import AutoTopUpConfig, TransactionHistoryfrom backend.data.org_credit import OrgCreditModel+from .billing.credits import routes as credits_routesfrom .v1 import v1_routerapp = fastapi.FastAPI()+# The credits routes now live in their own module; the subscription routes+# this suite also covers are still on v1_router until #14477 moves them.app.include_router(v1_router)+app.include_router(credits_routes.router)client = fastapi.testclient.TestClient(app)ORG_ID = "test-org"@@ -216,15 +220,22 @@ def credit_stubs(mocker: pytest_mock.MockFixture) -> CreditStubs:return_value="https://billing.example.com/portal")model.get_refund_requests = AsyncMock(return_value=[])+ # manage_payment_method is still on v1_router until #14477 moves the+ # subscription section, and it resolves v1's own get_credit_model — so the+ # suite spans two modules and both bindings need stubbing.+ mocker.patch("backend.api.features.v1.get_credit_model", return_value=model)return CreditStubs(get_credit_model=mocker.patch(- "backend.api.features.v1.get_credit_model", return_value=model+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=model,),get_auto_top_up=mocker.patch(- "backend.api.features.v1.get_auto_top_up",+ "backend.api.features.billing.credits.routes.get_auto_top_up",return_value=AutoTopUpConfig(amount=500, threshold=100),),- set_auto_top_up=mocker.patch("backend.api.features.v1.set_auto_top_up"),+ set_auto_top_up=mocker.patch(+ "backend.api.features.billing.credits.routes.set_auto_top_up"+ ),model=model,)@@ -331,6 +342,36 @@ def _enforced_org_actions(dependant: Dependant) -> set[OrgAction]:return enforced+# The eight /api/credits* routes served by modules other than the credits+# router. T250.2's audit (SECRT-2650) found none of them needs MANAGE_BILLING,+# so they are asserted by WHAT makes them safe rather than listed by name: a+# name survives the removal of the thing that justified it, which is the latent+# defect in UNGATED_CREDITS_ROUTES above.+ADMIN_CREDITS_ROUTES = {+ "add_user_credits",+ "admin_get_all_user_history",+ "export_copilot_weekly_usage",+ "export_credit_transactions",+}+TRIAL_CREDITS_ROUTES = {+ "cancel_trial",+ "confirm_trial",+ "get_trial_status",+ "start_trial_checkout",+}+++def _dependency_names(dependant: Dependant) -> set[str]:+ """Every dependency call name in a route's flattened tree."""+ names: set[str] = set()+ for sub_dep in dependant.dependencies:+ call = sub_dep.call+ if call is not None:+ names.add(getattr(call, "__name__", type(call).__name__))+ names |= _dependency_names(sub_dep)+ return names++def test_every_credits_route_is_gated_or_explicitly_exempt():"""Introspect the mounted app so a *new* ungated /credits route fails.@@ -339,27 +380,41 @@ def test_every_credits_route_is_gated_or_explicitly_exempt():table instead: every ``/credits*`` route must either carry the MANAGE_BILLINGdependency or be an explicit, documented exemption.- Scope, deliberately: this walks ``v1_router``'s own mount, not the real app,- so it does not see the eight ``/api/credits*`` routes served by other modules- (admin, trials, exports). Widening it to ``real_app`` makes all eight- unexpected at once and needs each audited against this rule on its own —- a security review, not a refactor, tracked as SECRT-2650. Until then this- cannot catch an ungated route outside ``v1_router``, and once the credits- section moves to its own module it will see nothing at all: that move must- mount ``real_app`` and carry the eight in a ``PENDING_AUDIT`` set, so a- ninth unexpected route still fails while none of the eight is signed off.+ It walks ``real_app``, not a locally-mounted router: this layer moves the+ credits routes out of ``v1_router``, so a ``v1_router``-only mount would see+ nothing at all here and pass vacuously. (#14475's docstring asked for a+ ``PENDING_AUDIT`` set of names; T250.2's audit then found none of the eight+ needs a gate, so they are asserted by what makes them safe instead — see+ ADMIN_CREDITS_ROUTES and TRIAL_CREDITS_ROUTES above, SECRT-2650.)++ A ninth unexpected ``/api/credits*`` route still fails this, which is the+ property the widening exists to restore."""gated: set[str] = set()ungated: set[str] = set()- for route in app.routes:- if not isinstance(route, APIRoute) or not route.path.startswith("/credits"):+ for route in real_app.routes:+ if not isinstance(route, APIRoute) or not route.path.startswith("/api/credits"):continueif OrgAction.MANAGE_BILLING in _enforced_org_actions(route.dependant):gated.add(route.name)+ elif route.name in ADMIN_CREDITS_ROUTES:+ # Safe because an admin JWT role claim gates it, which no org role+ # reaches — assert that, not the name.+ assert "requires_admin_user" in _dependency_names(route.dependant), (+ f"{route.name} is treated as admin-gated but no longer resolves "+ "requires_admin_user; it now needs MANAGE_BILLING or its own reason"+ )+ elif route.name in TRIAL_CREDITS_ROUTES:+ # Safe because it resolves no org context at all, so there is no+ # pooled balance for it to read.+ assert "get_request_context" not in _dependency_names(route.dependant), (+ f"{route.name} now resolves an org context; it can reach pooled "+ "credit and needs gating or its own documented reason"+ )else:ungated.add(route.name)- assert gated, "no /credits routes found — did the router or prefix change?"+ assert gated, "no /api/credits routes found — did the router or prefix change?"assert ungated == set(UNGATED_CREDITS_ROUTES), ("A /credits route is not behind MANAGE_BILLING. Gate it with ""`ctx: BillingManagerContext`, or — if it is genuinely not org-pooled "diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex 9234078390..2c2211944b 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -1,7 +1,7 @@import jsonfrom datetime import datetime, timezonefrom io import BytesIO-from unittest.mock import ANY, AsyncMock, Mock, patch+from unittest.mock import AsyncMock, Mock, patchimport fastapiimport fastapi.testclient@@ -13,7 +13,6 @@ from fastapi import HTTPException, UploadFilefrom pytest_snapshot.plugin import Snapshotfrom backend.api.rest_api import handle_internal_http_error-from backend.data.credit import AutoTopUpConfigfrom backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationErrorfrom backend.util.exceptions import ConflictError, InsufficientBalanceError@@ -430,283 +429,6 @@ def test_execute_graph_block_not_found(assert "not found" in response.json()["detail"]-# Credits endpoints tests-def test_get_user_credits(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,-) -> None:- """Test get user credits endpoint"""- mock_credit_model = Mock()- mock_credit_model.get_credits = AsyncMock(return_value=1000)- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- response = client.get("/credits")-- assert response.status_code == 200- response_data = response.json()- assert response_data["credits"] == 1000-- snapshot.snapshot_dir = "snapshots"- snapshot.assert_match(- json.dumps(response_data, indent=2, sort_keys=True),- "cred_bal",- )---def test_request_top_up(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,-) -> None:- """Test request top up endpoint"""- mock_credit_model = Mock()- mock_credit_model.top_up_intent = AsyncMock(- return_value="https://checkout.example.com/session123"- )- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- request_data = {"credit_amount": 500}-- response = client.post("/credits", json=request_data)-- assert response.status_code == 200- response_data = response.json()- assert "checkout_url" in response_data-- snapshot.snapshot_dir = "snapshots"- snapshot.assert_match(- json.dumps(response_data, indent=2, sort_keys=True),- "cred_topup_req",- )---def test_request_top_up_forwards_datafast_headers(- mocker: pytest_mock.MockFixture,-) -> None:- """DataFast attribution headers are forwarded to top_up_intent."""- mock_credit_model = Mock()- mock_credit_model.top_up_intent = AsyncMock(- return_value="https://checkout.example.com/session123"- )- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- response = client.post(- "/credits",- json={"credit_amount": 500},- headers={- "X-Datafast-Visitor-Id": "vis_1",- "X-Datafast-Session-Id": "ses_1",- },- )-- assert response.status_code == 200- mock_credit_model.top_up_intent.assert_awaited_once_with(- ANY,- 500,- datafast_visitor_id="vis_1",- datafast_session_id="ses_1",- )---def test_get_auto_top_up(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,-) -> None:- """Test get auto top-up configuration endpoint"""- mock_config = AutoTopUpConfig(threshold=100, amount=500)-- mocker.patch(- "backend.api.features.v1.get_auto_top_up",- return_value=mock_config,- )-- response = client.get("/credits/auto-top-up")-- assert response.status_code == 200- response_data = response.json()- assert response_data["threshold"] == 100- assert response_data["amount"] == 500-- snapshot.snapshot_dir = "snapshots"- snapshot.assert_match(- json.dumps(response_data, indent=2, sort_keys=True),- "cred_topup_cfg",- )---def test_configure_auto_top_up(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,-) -> None:- """Test configure auto top-up endpoint - this test would have caught the enum casting bug"""- # Mock the set_auto_top_up function to avoid database operations- mocker.patch(- "backend.api.features.v1.set_auto_top_up",- return_value=None,- )-- # Mock credit model to avoid Stripe API calls- mock_credit_model = mocker.AsyncMock()- mock_credit_model.get_credits.return_value = 50 # Current balance below threshold- mock_credit_model.top_up_credits.return_value = None-- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- # Test data- request_data = {- "threshold": 100,- "amount": 500,- }-- response = client.post("/credits/auto-top-up", json=request_data)-- # This should succeed with our fix, but would have failed before with the enum casting error- assert response.status_code == 200- assert response.json() == "Auto top-up settings updated"---def test_configure_auto_top_up_refuses_when_model_has_no_payment_path(- mocker: pytest_mock.MockFixture,-) -> None:- set_auto_top_up = mocker.patch("backend.api.features.v1.set_auto_top_up")-- mock_credit_model = mocker.AsyncMock()- mock_credit_model.get_credits.return_value = 50- mock_credit_model.top_up_credits.side_effect = NotImplementedError(- "Org-level Stripe top-up not yet implemented"- )- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- response = client.post(- "/credits/auto-top-up", json={"threshold": 500, "amount": 500}- )-- assert response.status_code == 501- set_auto_top_up.assert_not_called()---def test_configure_auto_top_up_validation_errors(- mocker: pytest_mock.MockFixture,-) -> None:- """Test configure auto top-up endpoint validation"""- # Mock set_auto_top_up to avoid database operations for successful case- mocker.patch("backend.api.features.v1.set_auto_top_up")-- # Mock credit model to avoid Stripe API calls for the successful case- mock_credit_model = mocker.AsyncMock()- mock_credit_model.get_credits.return_value = 50- mock_credit_model.top_up_credits.return_value = None-- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- # Test negative threshold- response = client.post(- "/credits/auto-top-up", json={"threshold": -1, "amount": 500}- )- assert response.status_code == 422 # Validation error-- # Test amount too small (but not 0)- response = client.post(- "/credits/auto-top-up", json={"threshold": 100, "amount": 100}- )- assert response.status_code == 422 # Validation error-- # Test amount = 0 (should be allowed)- response = client.post("/credits/auto-top-up", json={"threshold": 100, "amount": 0})- assert response.status_code == 200 # Should succeed---def test_list_invoices_returns_mapped_payload(- mocker: pytest_mock.MockFixture,-) -> None:- """The /credits/invoices route should return whatever the credit model- yields, serialised through the InvoiceListItem schema."""- from backend.data.credit import InvoiceListItem-- invoice = InvoiceListItem(- id="in_1",- number="INV-001",- created_at=datetime(2026, 4, 1, tzinfo=timezone.utc),- total_cents=2500,- amount_paid_cents=0,- currency="usd",- status="open",- description="Subscription",- hosted_invoice_url="https://invoice.stripe.com/i/test",- invoice_pdf_url="https://invoice.stripe.com/i/test/pdf",- )-- mock_credit_model = Mock()- mock_credit_model.list_invoices = AsyncMock(return_value=[invoice])- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- response = client.get("/credits/invoices?limit=24")-- assert response.status_code == 200- payload = response.json()- assert len(payload) == 1- row = payload[0]- assert row["id"] == "in_1"- assert row["total_cents"] == 2500- assert row["amount_paid_cents"] == 0- assert row["status"] == "open"- assert row["hosted_invoice_url"] == "https://invoice.stripe.com/i/test"- mock_credit_model.list_invoices.assert_awaited_once()- # Ensure the limit query param is forwarded.- assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}---def test_list_invoices_clamps_limit(mocker: pytest_mock.MockFixture) -> None:- """FastAPI's Query(le=100) should reject limit > 100."""- mock_credit_model = Mock()- mock_credit_model.list_invoices = AsyncMock(return_value=[])- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- response = client.get("/credits/invoices?limit=500")-- assert response.status_code == 422 # Validation error- mock_credit_model.list_invoices.assert_not_awaited()---def test_list_invoices_default_limit(mocker: pytest_mock.MockFixture) -> None:- """Omitting ?limit should default to 24."""- mock_credit_model = Mock()- mock_credit_model.list_invoices = AsyncMock(return_value=[])- mocker.patch(- "backend.api.features.v1.get_credit_model",- return_value=mock_credit_model,- )-- response = client.get("/credits/invoices")-- assert response.status_code == 200- assert response.json() == []- assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}--# Invalid request testsdef test_invalid_json_request() -> None:"""Test endpoint with invalid JSON"""@@ -718,12 +440,6 @@ def test_invalid_json_request() -> None:assert response.status_code == 422-def test_missing_required_field() -> None:- """Test endpoint with missing required field"""- response = client.post("/credits", json={}) # Missing credit_amount- assert response.status_code == 422--@pytest.mark.asyncioasync def test_upload_file_success(test_user_id: str):"""Test successful file upload."""diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 939b623f05..e4c913b148 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -30,6 +30,7 @@ import backend.api.features.admin.store_admin_routesimport backend.api.features.admin.test_data_routesimport backend.api.features.api_keys.routes as api_keys_routesimport backend.api.features.auth_email.routes as auth_email_routes+import backend.api.features.billing.credits.routes as credits_routesimport backend.api.features.briefings.routesimport backend.api.features.builderimport backend.api.features.builder.routes@@ -415,6 +416,11 @@ app.include_router(tags=["v1", "graphs"],prefix="/api",)+app.include_router(+ credits_routes.router,+ tags=["v1", "credits"],+ prefix="/api",+)app.include_router(auth_email_routes.auth_email_router,prefix="/api/auth/email",