Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): hide the pooled org balance on /home from members without MANAGE_BILLING (#14634)

Reinier van der Leer9f73c9090301
diff --git a/autogpt_platform/backend/backend/api/features/home/routes.py b/autogpt_platform/backend/backend/api/features/home/routes.py
index 43e5e704d7..ba6cbbb7c1 100644
--- a/autogpt_platform/backend/backend/api/features/home/routes.py
+++ b/autogpt_platform/backend/backend/api/features/home/routes.py
@@ -18,6 +18,6 @@ async def get_home_dashboard(
user_id: str = Security(autogpt_auth_lib.get_user_id),
ctx: RequestContext = Security(get_request_context),
) -> HomeDashboardResponse:
- # `organization_id` only selects the credit model; every other source on this
- # page is owner-scoped.
- return await build_home_dashboard(user_id=user_id, organization_id=ctx.org_id)
+ # The context selects the credit model and gates the pooled org balance;
+ # every other source on this page is owner-scoped.
+ return await build_home_dashboard(user_id=user_id, ctx=ctx)
diff --git a/autogpt_platform/backend/backend/api/features/home/routes_test.py b/autogpt_platform/backend/backend/api/features/home/routes_test.py
index 1b394c80bf..3cfcc824d0 100644
--- a/autogpt_platform/backend/backend/api/features/home/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/routes_test.py
@@ -92,7 +92,10 @@ def test_get_home_dashboard_returns_single_payload(
assert body["timezone"] == "UTC"
assert body["attention"][0]["kind"] == "approval"
assert set(body) >= {"attention", "briefing", "active_tasks", "team", "week"}
- build.assert_awaited_once_with(user_id=test_user_id, organization_id="test-org")
+ build.assert_awaited_once()
+ kwargs = build.await_args.kwargs
+ assert kwargs["user_id"] == test_user_id
+ assert kwargs["ctx"].org_id == "test-org"
def test_personal_context_passes_no_organization(
@@ -118,4 +121,7 @@ def test_personal_context_passes_no_organization(
)
assert client.get("/home").status_code == 200
- build.assert_awaited_once_with(user_id=test_user_id, organization_id=None)
+ build.assert_awaited_once()
+ kwargs = build.await_args.kwargs
+ assert kwargs["user_id"] == test_user_id
+ assert kwargs["ctx"].org_id is None
diff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.py
index 259d5336b9..6d1af50717 100644
--- a/autogpt_platform/backend/backend/api/features/home/service.py
+++ b/autogpt_platform/backend/backend/api/features/home/service.py
@@ -4,6 +4,8 @@ from datetime import datetime, timedelta, timezone
from typing import Any
from zoneinfo import ZoneInfo
+from autogpt_libs.auth.models import RequestContext
+from autogpt_libs.auth.permissions import OrgAction, check_org_permission
from pydantic import BaseModel, ValidationError
from backend.api.features.experts import experts_db
@@ -61,13 +63,13 @@ class HomeSourceData(BaseModel):
async def build_home_dashboard(
*,
user_id: str,
- organization_id: str | None = None,
+ ctx: RequestContext | None = None,
) -> HomeDashboardResponse:
now = datetime.now(timezone.utc)
week_start = now - timedelta(days=7)
data = await _load_home_source_data(
user_id=user_id,
- organization_id=organization_id,
+ ctx=ctx,
now=now,
week_start=week_start,
)
@@ -155,7 +157,7 @@ async def _persisted_briefing(
async def _load_home_source_data(
*,
user_id: str,
- organization_id: str | None,
+ ctx: RequestContext | None,
now: datetime,
week_start: datetime,
) -> HomeSourceData:
@@ -180,9 +182,7 @@ async def _load_home_source_data(
)
)
schedules_task = asyncio.create_task(_get_schedules(user_id=user_id))
- credits_task = asyncio.create_task(
- _get_credits(user_id=user_id, organization_id=organization_id)
- )
+ credits_task = asyncio.create_task(_get_credits(user_id=user_id, ctx=ctx))
questions_task = asyncio.create_task(_get_pending_questions(user_id=user_id))
work_events_task = asyncio.create_task(
_get_work_events(user_id=user_id, since=week_start)
@@ -285,7 +285,13 @@ async def _get_session_titles(
return {}
-async def _get_credits(*, user_id: str, organization_id: str | None) -> int | None:
+async def _get_credits(*, user_id: str, ctx: RequestContext | None) -> int | None:
+ # An org wallet is pooled and MANAGE_BILLING gates it on /credits, so a
+ # member without that permission must not read the same figure here.
+ # Personal orgs are unaffected: their membership row is always isOwner.
+ if ctx and ctx.org_id and not check_org_permission(ctx, OrgAction.MANAGE_BILLING):
+ return None
+ organization_id = ctx.org_id if ctx else None
try:
model = await get_credit_model(user_id, organization_id)
return await model.get_credits(user_id, organization_id)
diff --git a/autogpt_platform/backend/backend/api/features/home/service_test.py b/autogpt_platform/backend/backend/api/features/home/service_test.py
index 2ae15ad669..71d60b4cbb 100644
--- a/autogpt_platform/backend/backend/api/features/home/service_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/service_test.py
@@ -2,6 +2,7 @@ from datetime import date, datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock
import pytest
+from autogpt_libs.auth.models import RequestContext
from pytest_mock import MockerFixture
from backend.copilot.briefing.models import BriefingContent, BriefingRunItem
@@ -376,7 +377,7 @@ async def test_schedules_stay_owner_scoped_inside_an_organization(
AsyncMock(return_value=credit_model),
)
- await build_home_dashboard(user_id="user-1", organization_id="org-1")
+ await build_home_dashboard(user_id="user-1", ctx=_org_ctx(is_org_owner=True))
# Executions, reviews and cost totals are personal, so a teammate's schedule
# would show an upcoming run whose outcome never lands anywhere else.
@@ -452,3 +453,93 @@ class TestPendingQuestionsFlagGate:
assert result == ["session-info"]
get_sessions.assert_awaited_once_with("user-1")
+
+
+def _org_ctx(
+ *,
+ org_id: str | None = "org-1",
+ is_org_owner: bool = False,
+ is_org_admin: bool = False,
+ is_org_billing_manager: bool = False,
+) -> RequestContext:
+ return RequestContext(
+ user_id="user-1",
+ org_id=org_id,
+ team_id=None,
+ is_org_owner=is_org_owner,
+ is_org_admin=is_org_admin,
+ is_org_billing_manager=is_org_billing_manager,
+ is_team_admin=False,
+ is_team_billing_manager=False,
+ seat_status="ACTIVE",
+ )
+
+
+class TestPooledOrgBalanceGate:
+ """An org wallet is pooled across its members and MANAGE_BILLING gates it
+ on /credits, which 403s a plain member. Home reads the same wallet, so it
+ owes that member no figure — and no error either: the rest of the
+ dashboard has to arrive intact."""
+
+ @pytest.mark.parametrize(
+ ("ctx", "expected_balance"),
+ [
+ (_org_ctx(is_org_owner=True), 100),
+ (_org_ctx(is_org_billing_manager=True), 100),
+ (_org_ctx(), None),
+ (_org_ctx(is_org_admin=True), None),
+ ],
+ ids=["owner", "billing-manager", "member", "admin"],
+ )
+ @pytest.mark.asyncio
+ async def test_only_manage_billing_reads_the_pooled_balance(
+ self,
+ mocker: MockerFixture,
+ home_dependencies,
+ ctx: RequestContext,
+ expected_balance: int | None,
+ ) -> None:
+ mocker.patch(
+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ credit_model = MagicMock()
+ credit_model.get_credits = AsyncMock(return_value=100)
+ get_credit_model = mocker.patch(
+ "backend.api.features.home.service.get_credit_model",
+ AsyncMock(return_value=credit_model),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1", ctx=ctx)
+
+ assert dashboard.week.credits_balance == expected_balance
+ # Withholding the figure means never reading the wallet, not reading it
+ # and dropping the answer.
+ assert get_credit_model.await_count == (0 if expected_balance is None else 1)
+ # Everything else on the page is owner-scoped and must survive the gate.
+ assert dashboard.briefing.outcomes[0].title == "Booked the flight."
+
+ @pytest.mark.asyncio
+ async def test_a_personal_org_keeps_its_own_wallet(
+ self, mocker: MockerFixture, home_dependencies
+ ) -> None:
+ """A personal org's one membership row is always isOwner, so the gate
+ never fires there and the owner still sees their user wallet."""
+ mocker.patch(
+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ credit_model = MagicMock()
+ credit_model.get_credits = AsyncMock(return_value=100)
+ get_credit_model = mocker.patch(
+ "backend.api.features.home.service.get_credit_model",
+ AsyncMock(return_value=credit_model),
+ )
+
+ dashboard = await build_home_dashboard(
+ user_id="user-1",
+ ctx=_org_ctx(org_id="personal-org", is_org_owner=True),
+ )
+
+ assert dashboard.week.credits_balance == 100
+ get_credit_model.assert_awaited_once_with("user-1", "personal-org")
diff --git a/autogpt_platform/backend/backend/api/features/orgs/db.py b/autogpt_platform/backend/backend/api/features/orgs/db.py
index cbc91473a5..f870135dc9 100644
--- a/autogpt_platform/backend/backend/api/features/orgs/db.py
+++ b/autogpt_platform/backend/backend/api/features/orgs/db.py
@@ -477,6 +477,13 @@ async def add_org_member(
invited_by: str | None = None,
) -> OrgMemberResponse:
"""Add a member to an organization and its default workspace."""
+ # A personal org bills the owner's own wallet, so a second member would
+ # spend it with no billing permission of their own.
+ if await prisma.organization.find_first(where={"id": org_id, "isPersonal": True}):
+ raise ValueError(
+ "Cannot add a member to a personal organization. Convert it first."
+ )
+
member = await prisma.orgmember.create(
data={
"orgId": org_id,
diff --git a/autogpt_platform/backend/backend/api/features/orgs/routes_test.py b/autogpt_platform/backend/backend/api/features/orgs/routes_test.py
index f5eaafa911..4231ed5b7b 100644
--- a/autogpt_platform/backend/backend/api/features/orgs/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/orgs/routes_test.py
@@ -498,6 +498,7 @@ class TestOrgDbMembers:
from backend.api.features.orgs.db import add_org_member
new_member = _make_member(userId=OTHER_USER_ID, user_email="[email protected]")
+ self.prisma.organization.find_first = AsyncMock(return_value=None)
self.prisma.orgmember.create = AsyncMock(return_value=new_member)
default_ws = _make_workspace(id="ws-default", isDefault=True)
self.prisma.team.find_first = AsyncMock(return_value=default_ws)
@@ -525,6 +526,7 @@ class TestOrgDbMembers:
from backend.api.features.orgs.db import add_org_member
new_member = _make_member(userId=OTHER_USER_ID)
+ self.prisma.organization.find_first = AsyncMock(return_value=None)
self.prisma.orgmember.create = AsyncMock(return_value=new_member)
self.prisma.team.find_first = AsyncMock(return_value=None)
self.prisma.teammember.create = AsyncMock()
@@ -534,6 +536,27 @@ class TestOrgDbMembers:
# No workspace member should have been created
self.prisma.teammember.create.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_add_member_to_personal_org_raises_value_error(self):
+ """A personal org bills the owner's own user wallet, so a second
+ member would spend it without holding MANAGE_BILLING anywhere."""
+ from backend.api.features.orgs.db import add_org_member
+
+ self.prisma.organization.find_first = AsyncMock(
+ return_value=_make_org(isPersonal=True)
+ )
+ self.prisma.orgmember.create = AsyncMock(
+ return_value=_make_member(userId=OTHER_USER_ID)
+ )
+ self.prisma.team.find_first = AsyncMock(return_value=None)
+ self.prisma.teammember.create = AsyncMock()
+
+ with pytest.raises(ValueError, match="Cannot add a member to a personal"):
+ await add_org_member(org_id=ORG_ID, user_id=OTHER_USER_ID)
+
+ self.prisma.orgmember.create.assert_not_called()
+ self.prisma.teammember.create.assert_not_called()
+
@pytest.mark.asyncio
async def test_remove_member_cascades_workspace_memberships(self):
from backend.api.features.orgs.db import remove_org_member
@@ -1225,6 +1248,7 @@ class TestInvitationAcceptance:
# Mock add_org_member chain
new_member = _make_member(userId=test_user_id)
+ self.prisma.organization.find_first = AsyncMock(return_value=None)
self.prisma.orgmember.create = AsyncMock(return_value=new_member)
self.prisma.team.find_first = AsyncMock(return_value=None)
self.prisma.orginvitation.update = AsyncMock()
@@ -1236,6 +1260,34 @@ class TestInvitationAcceptance:
assert data["orgId"] == ORG_ID
assert "accepted" in data["message"].lower()
+ @pytest.mark.asyncio
+ async def test_accept_invitation_into_a_personal_org_raises_value_error(
+ self, test_user_id
+ ):
+ """Accepting creates the same OrgMember row POST /members does, so the
+ personal-org guard has to cover this path too."""
+ from backend.api.features.orgs.invitation_routes import accept_invitation
+
+ self.prisma.orginvitation.find_unique = AsyncMock(
+ return_value=self._make_invitation(email="[email protected]")
+ )
+ self.prisma.user.find_unique = AsyncMock(
+ return_value=MagicMock(id=test_user_id, email="[email protected]")
+ )
+ self.prisma.organization.find_first = AsyncMock(
+ return_value=_make_org(isPersonal=True)
+ )
+ self.prisma.orgmember.create = AsyncMock(
+ return_value=_make_member(userId=test_user_id)
+ )
+ self.prisma.team.find_first = AsyncMock(return_value=None)
+ self.prisma.orginvitation.update = AsyncMock()
+
+ with pytest.raises(ValueError, match="Cannot add a member to a personal"):
+ await accept_invitation("tok-abc", user_id=test_user_id)
+
+ self.prisma.orgmember.create.assert_not_called()
+
def test_accept_expired_invitation_raises(self, _app_and_client):
_, client = _app_and_client