AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): gate org credits routes behind MANAGE_BILLING (#13527)
Nicholas Tindle4b8f0c32c51c
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex f1062108a2..cdf9361d94 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -9,9 +9,15 @@ from urllib.parse import urlparseimport pydanticimport stripe-from autogpt_libs.auth import get_request_context, get_user_id, requires_user+from autogpt_libs.auth import (+ get_request_context,+ get_user_id,+ requires_org_permission,+ requires_user,+)from 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,@@ -711,6 +717,20 @@ 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"],@@ -719,7 +739,7 @@ async def upload_file()async def get_user_credits(user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ 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)}@@ -734,7 +754,7 @@ async def get_user_credits(async def request_top_up(request: RequestTopUp,user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,x_datafast_visitor_id: Annotated[str | None, Header(include_in_schema=False)] = None,@@ -760,7 +780,7 @@ async def request_top_up()async def refund_top_up(user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,transaction_key: str,metadata: dict[str, str],) -> int:@@ -776,7 +796,7 @@ async def refund_top_up()async def fulfill_checkout(user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,):credit_model = await get_credit_model(user_id, ctx.org_id)await credit_model.fulfill_checkout(user_id=user_id)@@ -792,7 +812,7 @@ async def fulfill_checkout(async def configure_user_auto_top_up(request: AutoTopUpConfig,user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,) -> str:"""Configure auto top-up settings and perform an immediate top-up if needed.@@ -1717,7 +1737,7 @@ async def manage_payment_method()async def get_credit_history(user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,transaction_time: datetime | None = None,transaction_type: str | None = None,transaction_count_limit: int = 100,@@ -1745,7 +1765,7 @@ async def get_credit_history()async def get_refund_requests(user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,) -> list[RefundRequest]:credit_model = await get_credit_model(user_id, ctx.org_id)return await credit_model.get_refund_requests(user_id)@@ -1759,14 +1779,18 @@ async def get_refund_requests()async def list_invoices(user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],+ ctx: BillingManagerContext,limit: int = Query(24, ge=1, le=100),) -> list[InvoiceListItem]:- """Recent Stripe invoices for the current user.+ """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 user has no Stripe customer yet.+ 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.pynew file mode 100644index 0000000000..2dd7894b8b--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py@@ -0,0 +1,456 @@+"""Authorization tests for the org-scoped credits routes in v1.py.++SECRT-2449: the credits balance/transaction/invoice/top-up routes resolve+their credit model through the request's org context, so for a real (pooled)+org they read/mutate the shared ``OrgBalance``. They must therefore require+org-level ``MANAGE_BILLING`` (owner or billing_manager) — a plain org member+must be rejected with 403. Personal-org owners always carry ``is_org_owner``,+so the gate is a no-op for them. The ``/credits`` routes that serve the+caller's own data rather than the org's are exempt, and say why in+``UNGATED_CREDITS_ROUTES``.++The gate is applied as an independent per-route dependency (there is no+shared router-level enforcement), so every gated route is asserted here:+dropping the dependency from any single route must fail this suite. Route+coverage is not left to the hand-maintained ``GATED_ROUTES`` list either —+two introspection tests walk the mounted app, so both a *newly added* ungated+``/credits`` route and a route reaching ``get_credit_model`` under any other+prefix fail.+"""++import inspect+from collections.abc import Callable+from typing import Any+from unittest.mock import AsyncMock, Mock++import fastapi+import fastapi.testclient+import pydantic+import pytest+import pytest_mock+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+from autogpt_libs.auth.permissions import OrgAction+from fastapi.dependencies.models import Dependant+from fastapi.routing import APIRoute++from backend.data.model import AutoTopUpConfig, TransactionHistory+from backend.data.org_credit import OrgCreditModel++from .v1 import v1_router++app = fastapi.FastAPI()+app.include_router(v1_router)+client = fastapi.testclient.TestClient(app)++ORG_ID = "test-org"+++def _ctx(+ user_id: str,+ *,+ owner: bool = False,+ admin: bool = False,+ billing: bool = False,+ org_id: str = ORG_ID,+) -> RequestContext:+ return RequestContext(+ user_id=user_id,+ org_id=org_id,+ team_id=None,+ is_org_owner=owner,+ is_org_admin=admin,+ is_org_billing_manager=billing,+ is_team_admin=False,+ is_team_billing_manager=False,+ seat_status="ACTIVE",+ )+++# role -> (RequestContext role flags, expected HTTP status).+#+# MANAGE_BILLING is granted to {owner, billing_manager} only (see+# autogpt_libs.auth.permissions._ORG_PERMISSIONS). ``org_admin`` is the+# important negative case: admins can rename the org and manage members but+# are deliberately excluded from billing, so widening the grant to admins must+# break this suite.+#+# Personal orgs are covered separately by the tests at the bottom of this+# module, which drive the *real* ``get_request_context`` resolution instead of+# overriding it — a role-flag row here could not tell a personal org apart+# from a team org, since the gate is a pure function of the role flags.+ROLE_CASES: dict[str, tuple[dict, int]] = {+ "org_owner": ({"owner": True, "admin": True}, 200),+ "billing_manager": ({"billing": True}, 200),+ "org_admin": ({"admin": True}, 403),+ "plain_member": ({}, 403),+}+++class GatedRoute(pydantic.BaseModel):+ """One MANAGE_BILLING-gated endpoint and how to exercise it."""++ name: str+ method: str+ path: str+ # Predicate on the success response, to prove the route body really ran.+ check_ok: Callable[[Any], bool]+ body: dict | None = None+++# Every route in v1.py carrying+# ``Security(requires_org_permission(OrgAction.MANAGE_BILLING))`` (via the+# ``BillingManagerContext`` alias). Kept in sync with the app by+# ``test_every_credits_route_is_gated_or_explicitly_exempt``; ``name`` is the+# endpoint function name, which is also the FastAPI route name.+GATED_ROUTES: list[GatedRoute] = [+ GatedRoute(+ name="get_user_credits",+ method="GET",+ path="/credits",+ check_ok=lambda r: r.json() == {"credits": 1000},+ ),+ GatedRoute(+ name="request_top_up",+ method="POST",+ path="/credits",+ body={"credit_amount": 500},+ check_ok=lambda r: r.json()["checkout_url"].startswith("https://"),+ ),+ GatedRoute(+ name="refund_top_up",+ method="POST",+ path="/credits/test-transaction-key/refund",+ body={"reason": "duplicate charge"},+ check_ok=lambda r: r.json() == 500,+ ),+ GatedRoute(+ name="fulfill_checkout",+ method="PATCH",+ path="/credits",+ check_ok=lambda r: r.content == b"",+ ),+ GatedRoute(+ name="configure_user_auto_top_up",+ method="POST",+ path="/credits/auto-top-up",+ body={"amount": 500, "threshold": 100},+ check_ok=lambda r: r.json() == "Auto top-up settings updated",+ ),+ GatedRoute(+ name="get_credit_history",+ method="GET",+ path="/credits/transactions",+ check_ok=lambda r: r.json()["transactions"] == [],+ ),+ GatedRoute(+ name="get_refund_requests",+ method="GET",+ path="/credits/refunds",+ check_ok=lambda r: r.json() == [],+ ),+ GatedRoute(+ name="list_invoices",+ method="GET",+ path="/credits/invoices",+ check_ok=lambda r: r.json() == [],+ ),+]+++# ``/credits*`` routes that are deliberately NOT behind MANAGE_BILLING, keyed+# by endpoint function name with the reason they are exempt. Adding an entry+# here is an explicit product decision, not a way to silence the introspection+# test below.+UNGATED_CREDITS_ROUTES: dict[str, str] = {+ "get_subscription_status": "subscriptions are user-level, not org-pooled",+ "update_subscription_tier": "subscriptions are user-level, not org-pooled",+ "stripe_webhook": "unauthenticated by design; verified by Stripe signature",+ "get_user_auto_top_up": "reads the caller's own User.top_up_config, not org data",+ "manage_payment_method": (+ "opens the caller's own Stripe portal; OrgCreditModel does not override "+ "create_billing_portal_session"+ ),+}+++class CreditStubs(pydantic.BaseModel):+ """Patched data-layer entry points reachable from the gated routes."""++ model_config = pydantic.ConfigDict(arbitrary_types_allowed=True)++ get_credit_model: AsyncMock+ get_auto_top_up: AsyncMock+ set_auto_top_up: AsyncMock+ model: Mock++[email protected](autouse=True)+def _auth(mock_jwt_user):+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()+++def credit_stubs(mocker: pytest_mock.MockFixture) -> CreditStubs:+ """Patch every data-layer call the gated routes make.++ ``get_credit_model``/``get_auto_top_up``/``set_auto_top_up`` are async+ functions, so ``mocker.patch`` yields AsyncMocks and+ ``await get_credit_model(...)`` resolves to ``model``.+ """+ model = Mock()+ model.get_credits = AsyncMock(return_value=1000)+ model.get_transaction_history = AsyncMock(+ return_value=TransactionHistory(transactions=[], next_transaction_time=None)+ )+ model.list_invoices = AsyncMock(return_value=[])+ model.top_up_intent = AsyncMock(return_value="https://checkout.example.com/s")+ model.top_up_refund = AsyncMock(return_value=500)+ model.top_up_credits = AsyncMock(return_value=None)+ model.fulfill_checkout = AsyncMock(return_value=None)+ model.create_billing_portal_session = AsyncMock(+ return_value="https://billing.example.com/portal"+ )+ model.get_refund_requests = AsyncMock(return_value=[])+ return CreditStubs(+ get_credit_model=mocker.patch(+ "backend.api.features.v1.get_credit_model", return_value=model+ ),+ get_auto_top_up=mocker.patch(+ "backend.api.features.v1.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"),+ model=model,+ )+++def _use_role(role: str, user_id: str) -> int:+ flags, expected = ROLE_CASES[role]+ ctx = _ctx(user_id, **flags)++ async def _override() -> RequestContext:+ return ctx++ app.dependency_overrides[get_request_context] = _override+ return expected++[email protected]("route", GATED_ROUTES, ids=lambda r: r.name)[email protected]("role", list(ROLE_CASES))+def test_credits_route_requires_manage_billing(+ role: str, route: GatedRoute, test_user_id: str, credit_stubs: CreditStubs+):+ expected = _use_role(role, test_user_id)++ resp = client.request(route.method, route.path, json=route.body)++ assert resp.status_code == expected, resp.text+ if expected == 200:+ assert route.check_ok(resp), resp.text+ # The org the gate resolved is what the credit model is scoped to, so a+ # wrong-org regression fails here on every gated route — not only in the+ # single personal-org resolution test below.+ assert credit_stubs.get_credit_model.await_args.args[1] == ORG_ID+ else:+ assert resp.json()["detail"] == "Missing org permission: MANAGE_BILLING"+ # The gate rejects during dependency resolution, before the route body+ # ever reaches the org-pooled balance.+ credit_stubs.get_credit_model.assert_not_awaited()+++ "path, expected_json",+ [+ ("/credits/auto-top-up", {"amount": 500, "threshold": 100}),+ ("/credits/manage", {"url": "https://billing.example.com/portal"}),+ ],+ ids=["get_user_auto_top_up", "manage_payment_method"],+)+def test_user_scoped_credits_route_allows_plain_member(+ path: str, expected_json: dict, test_user_id: str, credit_stubs: CreditStubs+):+ """The two GETs that serve the caller's own data must stay ungated.++ ``get_auto_top_up`` reads the caller's ``User.top_up_config`` and+ ``create_billing_portal_session`` is not overridden by ``OrgCreditModel``,+ so it mints a portal for the caller's own Stripe customer. Gating either+ would deny a plain member their own settings while protecting no org data.+ """+ _use_role("plain_member", test_user_id)++ resp = client.get(path)++ assert resp.status_code == 200, resp.text+ assert resp.json() == expected_json+++ "route_name, call",+ [+ ("request_top_up", lambda m: m.top_up_intent("user-1", 500)),+ ("refund_top_up", lambda m: m.top_up_refund("user-1", "key", {})),+ ("fulfill_checkout", lambda m: m.fulfill_checkout(user_id="user-1")),+ ],+ ids=["request_top_up", "refund_top_up", "fulfill_checkout"],+)+async def test_gated_top_up_route_is_unimplemented_for_pooled_orgs(+ route_name: str, call: Callable[[OrgCreditModel], Any]+):+ """The 200 rows above run on a mocked model; a real pooled org cannot.++ ``OrgCreditModel`` has no Stripe top-up, so a billing manager who passes the+ gate still cannot top up a pooled org. Asserting it here keeps the mocked+ happy path above from reading as a working feature.+ """+ assert route_name in {route.name for route in GATED_ROUTES}+ with pytest.raises(NotImplementedError):+ await call(OrgCreditModel(ORG_ID))+++def _enforced_org_actions(dependant: Dependant) -> set[OrgAction]:+ """Org actions enforced by a route's dependency tree.++ ``requires_org_permission(*actions)`` returns a closure, so the actions it+ enforces are read back off the closure rather than re-derived from the+ route signature.+ """+ enforced: set[OrgAction] = set()+ for sub in dependant.dependencies:+ call = sub.call+ if (+ inspect.isfunction(call)+ and call.__qualname__ == "requires_org_permission.<locals>._dependency"+ ):+ enforced.update(inspect.getclosurevars(call).nonlocals["actions"])+ enforced |= _enforced_org_actions(sub)+ return enforced+++def test_every_credits_route_is_gated_or_explicitly_exempt():+ """Introspect the mounted app so a *new* ungated /credits route fails.++ ``GATED_ROUTES`` above is hand-maintained, so on its own it can only prove+ that the routes someone remembered to list are gated. This walks the real+ routing table instead: every ``/credits*`` route must either carry the+ MANAGE_BILLING dependency or be an explicit, documented exemption.+ """+ gated: set[str] = set()+ ungated: set[str] = set()+ for route in app.routes:+ if not isinstance(route, APIRoute) or not route.path.startswith("/credits"):+ continue+ if OrgAction.MANAGE_BILLING in _enforced_org_actions(route.dependant):+ gated.add(route.name)+ else:+ ungated.add(route.name)++ assert gated, "no /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 "+ "— add it to UNGATED_CREDITS_ROUTES with the reason. Unexpected: "+ f"{sorted(ungated - set(UNGATED_CREDITS_ROUTES))}"+ )+ assert gated == {route.name for route in GATED_ROUTES}, (+ "GATED_ROUTES is out of sync with the routes actually carrying the "+ "MANAGE_BILLING dependency; add the new route to GATED_ROUTES so the "+ "role matrix exercises it: "+ f"{sorted(gated ^ {route.name for route in GATED_ROUTES})}"+ )+++# Routes that resolve the org-pooled credit model without the gate, with the+# reason. Anything else reaching ``get_credit_model`` must be gated.+ORG_BALANCE_UNGATED: dict[str, str] = {+ "execute_graph": (+ "the executor spends the pooled balance; gating it would stop plain "+ "members running agents, and it reveals no balance (402 only)"+ ),+ "manage_payment_method": UNGATED_CREDITS_ROUTES["manage_payment_method"],+}+++def test_every_org_balance_reader_is_gated_or_explicitly_exempt():+ """Catch org-pooled balance access outside the ``/credits`` prefix.++ The path-prefix test above cannot see ``execute_graph``, which already reads+ the pooled balance from ``/graphs/{id}/execute``, nor a future org-billing+ route under another prefix.+ """+ ungated = {+ route.name+ for route in app.routes+ if isinstance(route, APIRoute)+ and "get_credit_model" in inspect.getsource(route.endpoint)+ and OrgAction.MANAGE_BILLING not in _enforced_org_actions(route.dependant)+ }++ assert ungated == set(ORG_BALANCE_UNGATED), (+ "A route resolves the org-pooled credit model without MANAGE_BILLING. "+ "Gate it with `ctx: BillingManagerContext`, or — if it genuinely serves "+ "the caller's own data — add it to ORG_BALANCE_UNGATED with the reason. "+ f"Unexpected: {sorted(ungated - set(ORG_BALANCE_UNGATED))}"+ )+++def _org_member(+ *, owner: bool = False, admin: bool = False, billing: bool = False+) -> Mock:+ """A prisma ``OrgMember`` row as ``get_request_context`` expects it."""+ row = Mock()+ row.status = "ACTIVE"+ row.isOwner = owner+ row.isAdmin = admin+ row.isBillingManager = billing+ row.Org = Mock(deletedAt=None)+ return row+++def mock_prisma(mocker: pytest_mock.MockFixture) -> Mock:+ """Stub the prisma client that the real ``get_request_context`` uses."""+ prisma = mocker.patch("backend.data.db.prisma")+ prisma.orgmember.find_first = AsyncMock(return_value=None)+ prisma.orgmember.find_unique = AsyncMock(return_value=None)+ return prisma+++def test_personal_org_owner_passes_real_context_resolution(+ mock_prisma: Mock, credit_stubs: CreditStubs+):+ """A personal-org user hits the real resolution path and is let through.++ No ``X-Org-Id`` header is sent, so ``get_request_context`` falls back to the+ user's personal org, whose membership row is always ``isOwner=True``. This+ deliberately does *not* override ``get_request_context``: the claim being+ tested is that the personal-org fallback yields owner rights, which a+ hand-built RequestContext could not prove.+ """+ mock_prisma.orgmember.find_first = AsyncMock(return_value=Mock(orgId="personal-1"))+ mock_prisma.orgmember.find_unique = AsyncMock(return_value=_org_member(owner=True))++ resp = client.get("/credits")++ assert resp.status_code == 200, resp.text+ assert resp.json() == {"credits": 1000}+ # The personal-org fallback ran (no X-Org-Id header was supplied) and its+ # org id is what the credit model was resolved against.+ mock_prisma.orgmember.find_first.assert_awaited_once()+ assert credit_stubs.get_credit_model.await_args.args[1] == "personal-1"+++def test_plain_member_of_shared_org_rejected_real_context_resolution(+ mock_prisma: Mock, credit_stubs: CreditStubs+):+ """The same real resolution path rejects a plain member of a pooled org."""+ mock_prisma.orgmember.find_unique = AsyncMock(return_value=_org_member())++ resp = client.get("/credits", headers={"X-Org-Id": "shared-org"})++ assert resp.status_code == 403, resp.text+ assert resp.json()["detail"] == "Missing org permission: MANAGE_BILLING"+ credit_stubs.get_credit_model.assert_not_awaited()diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex dfc80d2d05..bc91fb4aa2 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -5529,7 +5529,7 @@"get": {"tags": ["v1", "credits"],"summary": "List Stripe invoices",- "description": "Recent Stripe invoices for the current user.\n\nEach item includes ``hosted_invoice_url`` (Stripe-hosted view) and\n``invoice_pdf_url`` (direct PDF download). Returns an empty list when\nthe credit system is disabled or the user has no Stripe customer yet.",+ "description": "Recent Stripe invoices for the caller's active org, for billing managers.\n\nThe invoices belong to the org the request resolves to (the caller's\npersonal org when no ``X-Org-Id`` is supplied), so this is restricted to\norg roles holding ``MANAGE_BILLING``.\n\nEach item includes ``hosted_invoice_url`` (Stripe-hosted view) and\n``invoice_pdf_url`` (direct PDF download). Returns an empty list when\nthe credit system is disabled or the org has no Stripe customer yet.","operationId": "getV1List stripe invoices","security": [{ "HTTPBearerJWT": [] }],"parameters": [