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(platform): stop Settings > Billing from creating a Stripe customer that gets admin-granted plans revoked (#15116)
Abhimanyu Yadave833c22a3bd7
diff --git a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.pyindex 58d65bec9a..54af3bde86 100644--- a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py+++ b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes.py@@ -1,5 +1,6 @@"""Admin endpoints for checking and resetting user CoPilot rate limit usage."""+import asyncioimport loggingfrom typing import Optional@@ -11,6 +12,7 @@ from backend.copilot.config import ChatConfigfrom backend.copilot.rate_limit import (SubscriptionTier,get_global_rate_limits,+ get_stripe_sweep_revert_warning,get_tier_multipliers,get_usage_status,get_user_tier,@@ -46,6 +48,10 @@ class UserRateLimitResponse(BaseModel):class UserTierResponse(BaseModel):user_id: strtier: SubscriptionTier+ # Set by POST /rate_limit/tier when the grant will not stick: the user has+ # a Stripe customer without an active subscription, so the Stripe+ # reconciliation sweep will revert the tier to NO_TIER on its next run.+ warning: Optional[str] = Noneclass SetUserTierRequest(BaseModel):@@ -238,7 +244,25 @@ async def set_user_rate_limit_tier(logger.exception("Failed to set user tier")raise HTTPException(status_code=500, detail="Failed to set tier") from e- return UserTierResponse(user_id=request.user_id, tier=request.tier)+ warning = await _sweep_revert_warning(request.user_id, request.tier)+ return UserTierResponse(user_id=request.user_id, tier=request.tier, warning=warning)+++async def _sweep_revert_warning(user_id: str, tier: SubscriptionTier) -> Optional[str]:+ """Best-effort: the tier is already written, so a Stripe or DB hiccup here+ must not turn the response into a 500 or hold the admin for long."""+ try:+ return await asyncio.wait_for(+ get_stripe_sweep_revert_warning(user_id, tier), timeout=5.0+ )+ except Exception:+ logger.warning(+ "Could not check whether the Stripe sweep will revert the tier grant"+ " for user %s",+ user_id,+ exc_info=True,+ )+ return Noneclass UserSearchResult(BaseModel):diff --git a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.pyindex 8b3db9d407..31c325c6b5 100644--- a/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/admin/rate_limit_admin_routes_test.py@@ -364,6 +364,77 @@ def test_set_user_tier(mock_set.assert_awaited_once_with(target_user_id, SubscriptionTier.ENTERPRISE)+def test_set_user_tier_returns_sweep_revert_warning(+ mocker: pytest_mock.MockerFixture,+ target_user_id: str,+) -> None:+ """A grant the Stripe sweep will undo is still written, and the response+ carries the warning so the admin UI can show it."""+ mocker.patch(+ f"{_MOCK_MODULE}.get_user_email_by_id",+ new_callable=AsyncMock,+ return_value=_TARGET_EMAIL,+ )+ mocker.patch(+ f"{_MOCK_MODULE}.get_user_tier",+ new_callable=AsyncMock,+ return_value=SubscriptionTier.NO_TIER,+ )+ mock_set = mocker.patch(+ f"{_MOCK_MODULE}.set_user_tier",+ new_callable=AsyncMock,+ )+ mock_warning = mocker.patch(+ f"{_MOCK_MODULE}.get_stripe_sweep_revert_warning",+ new_callable=AsyncMock,+ return_value="The Stripe reconciliation sweep will revert this grant.",+ )++ response = client.post(+ "/admin/rate_limit/tier",+ json={"user_id": target_user_id, "tier": "PRO"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["tier"] == "PRO"+ assert data["warning"] == "The Stripe reconciliation sweep will revert this grant."+ mock_set.assert_awaited_once_with(target_user_id, SubscriptionTier.PRO)+ mock_warning.assert_awaited_once_with(target_user_id, SubscriptionTier.PRO)+++def test_set_user_tier_warning_lookup_failure_does_not_fail_request(+ mocker: pytest_mock.MockerFixture,+ target_user_id: str,+) -> None:+ """The tier is already written when the check runs, so a Stripe or DB+ error there degrades to no warning rather than a 500."""+ mocker.patch(+ f"{_MOCK_MODULE}.get_user_email_by_id",+ new_callable=AsyncMock,+ return_value=_TARGET_EMAIL,+ )+ mocker.patch(+ f"{_MOCK_MODULE}.get_user_tier",+ new_callable=AsyncMock,+ return_value=SubscriptionTier.NO_TIER,+ )+ mocker.patch(f"{_MOCK_MODULE}.set_user_tier", new_callable=AsyncMock)+ mocker.patch(+ f"{_MOCK_MODULE}.get_stripe_sweep_revert_warning",+ new_callable=AsyncMock,+ side_effect=RuntimeError("stripe down"),+ )++ response = client.post(+ "/admin/rate_limit/tier",+ json={"user_id": target_user_id, "tier": "PRO"},+ )++ assert response.status_code == 200+ assert response.json()["warning"] is None++def test_set_user_tier_downgrade(mocker: pytest_mock.MockerFixture,target_user_id: str,diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.pyindex fc0bbd0bcb..ee698d78bb 100644--- a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py@@ -912,6 +912,12 @@ async def stripe_webhook(request: Request):async def manage_payment_method(user_id: Annotated[str, Security(get_user_id)],ctx: Annotated[RequestContext, Security(get_request_context)],-) -> dict[str, str]:+) -> dict[str, str | None]:+ """Return a Stripe billing-portal URL for the caller.++ ``url`` is ``None`` when the user has no Stripe customer yet: this route is+ requested on every Settings > Billing load, so it must never provision a+ customer as a side effect (see ``create_billing_portal_session``).+ """credit_model = await get_credit_model(user_id, ctx.org_id)return {"url": await credit_model.create_billing_portal_session(user_id)}diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.pyindex fae1ff2326..67a883593e 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py@@ -55,6 +55,7 @@ import asyncioimport loggingfrom datetime import UTC, datetime, timedeltafrom enum import Enum+from typing import TYPE_CHECKINGimport fastapifrom autogpt_libs.auth.dependencies import get_user_id@@ -71,6 +72,9 @@ from backend.util.cache import cachedfrom backend.util.exceptions import UserPaywalledErrorfrom backend.util.feature_flag import Flag, get_feature_flag_value, is_feature_enabled+if TYPE_CHECKING:+ import stripe+logger = logging.getLogger(__name__)# "copilot:cost" (not the legacy "copilot:usage") so stale token-based@@ -1176,6 +1180,90 @@ async def _warn_if_stripe_subscription_drifts()+async def get_stripe_sweep_revert_warning(+ user_id: str, tier: SubscriptionTier+) -> str | None:+ """Explain when the Stripe reconciliation sweep would undo an admin grant.++ The sweep treats every user who has a Stripe customer (other than+ ENTERPRISE) as Stripe-billed and sets their tier from the live+ subscription: the tier of the subscription's price, NO_TIER when there is+ no active or trialing subscription. Two admin grants are therefore+ reverted on the next sweep, silently:++ - a paid tier on a user with a customer but no subscription (an old+ top-up, a canceled plan) goes back to NO_TIER;+ - a tier that differs from the user's live subscription (MAX granted to a+ PRO payer) goes back to the subscription's tier.++ Returns a message for the admin in either case, None when the grant is+ safe. A subscription whose price is not in the configured tier map (a+ trial enrollment, an unknown price) yields None: what the sweep does with+ it depends on state this check cannot see, so it stays quiet rather than+ guess.++ Raises on Stripe/DB failure; the caller decides how to degrade.+ """+ if tier in (SubscriptionTier.NO_TIER, SubscriptionTier.ENTERPRISE):+ return None+ # Local import: breaks a credit <-> rate_limit circular at module load.+ from backend.data.credit import _get_active_subscription, build_price_to_tier_map++ user = await get_user_by_id(user_id)+ if not user.stripe_customer_id:+ return None+ sub = await _get_active_subscription(user.stripe_customer_id)+ if sub is None:+ logger.warning(+ "Admin tier grant will be reverted by the Stripe sweep: user=%s"+ " admin_tier=%s stripe_customer=%s has no active subscription",+ user_id,+ tier.value,+ user.stripe_customer_id,+ )+ return (+ "This user already has a Stripe customer with no active subscription. "+ "The Stripe reconciliation sweep treats such accounts as Stripe-billed "+ f"and will revert this {tier.value} grant to NO_TIER within "+ f"{_sweep_interval_text()}. Use ENTERPRISE for a plan Stripe must not "+ "manage, or give the user a real Stripe subscription."+ )+ stripe_tier = (await build_price_to_tier_map()).get(_subscription_price_id(sub))+ if stripe_tier is None or stripe_tier == tier:+ return None+ logger.warning(+ "Admin tier grant will be reverted by the Stripe sweep: user=%s"+ " admin_tier=%s stripe_customer=%s stripe_sub=%s is on %s",+ user_id,+ tier.value,+ user.stripe_customer_id,+ sub.id,+ stripe_tier.value,+ )+ return (+ f"This user has an active Stripe subscription on {stripe_tier.value}. "+ "The Stripe reconciliation sweep sets the tier from that subscription "+ f"and will revert this {tier.value} grant to {stripe_tier.value} within "+ f"{_sweep_interval_text()}. Use ENTERPRISE for a plan Stripe must not "+ "manage, or change the user's Stripe subscription instead."+ )+++def _subscription_price_id(sub: "stripe.Subscription") -> str:+ items = sub["items"].data+ if not items:+ return ""+ price = items[0].price+ return price if isinstance(price, str) else price.id+++def _sweep_interval_text() -> str:+ from backend.util.settings import Config++ hours = Config().stripe_tier_reconcile_interval_hours+ return f"{hours} hour{'s' if hours != 1 else ''}"++async def get_global_rate_limits(user_id: str,config_daily: int,diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.pyindex 396a2c20f1..f7e64af24f 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py@@ -3041,3 +3041,198 @@ class TestBuildBudgetCtx:default_weekly_cost_limit=1_000_000_000,)assert block == ""+++# ---------------------------------------------------------------------------+# get_stripe_sweep_revert_warning — admin grant vs. the Stripe sweep+# ---------------------------------------------------------------------------+++class TestGetStripeSweepRevertWarning:+ """The Stripe reconciliation sweep sets every Stripe-customer user's tier+ from their live subscription (SECRT-2770): a paid grant on a user with no+ subscription goes back to NO_TIER, and a grant that differs from an active+ subscription goes back to that subscription's tier. Admins granting either+ must be told, since nothing else surfaces the revert."""++ @staticmethod+ def _user(stripe_customer_id: str | None) -> MagicMock:+ user = MagicMock()+ user.stripe_customer_id = stripe_customer_id+ return user++ @staticmethod+ def _sub(price_id: str) -> MagicMock:+ item = MagicMock()+ item.price = price_id+ items = MagicMock()+ items.data = [item]+ sub = MagicMock(id="sub_1")+ sub.__getitem__.side_effect = lambda key: {"items": items}[key]+ return sub++ @pytest.mark.asyncio+ async def test_warns_when_customer_has_no_active_subscription(self, caplog):+ from backend.copilot.rate_limit import get_stripe_sweep_revert_warning++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=self._user("cus_old_topup"),+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ return_value=None,+ ) as active_sub,+ patch("backend.util.settings.Config") as config_cls,+ ):+ config_cls.return_value.stripe_tier_reconcile_interval_hours = 6+ with caplog.at_level("WARNING", logger="backend.copilot.rate_limit"):+ warning = await get_stripe_sweep_revert_warning(+ _USER, SubscriptionTier.PRO+ )++ active_sub.assert_awaited_once_with("cus_old_topup")+ assert warning is not None+ assert "PRO" in warning+ assert "NO_TIER" in warning+ assert "6 hours" in warning+ assert "ENTERPRISE" in warning+ assert any(+ "will be reverted by the Stripe sweep" in r.getMessage()+ for r in caplog.records+ )++ @pytest.mark.asyncio+ async def test_warns_when_active_subscription_is_on_another_tier(self, caplog):+ """MAX granted to a paying PRO user: the sweep puts them back on PRO."""+ from backend.copilot.rate_limit import get_stripe_sweep_revert_warning++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=self._user("cus_paying"),+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ return_value=self._sub("price_pro_monthly"),+ ),+ patch(+ "backend.data.credit.build_price_to_tier_map",+ new_callable=AsyncMock,+ return_value={+ "price_pro_monthly": SubscriptionTier.PRO,+ "price_max_monthly": SubscriptionTier.MAX,+ },+ ),+ patch("backend.util.settings.Config") as config_cls,+ ):+ config_cls.return_value.stripe_tier_reconcile_interval_hours = 1+ with caplog.at_level("WARNING", logger="backend.copilot.rate_limit"):+ warning = await get_stripe_sweep_revert_warning(+ _USER, SubscriptionTier.MAX+ )++ assert warning is not None+ assert "MAX grant to PRO" in warning+ assert "NO_TIER" not in warning+ assert "1 hour." in warning+ assert any(+ "will be reverted by the Stripe sweep" in r.getMessage()+ and "is on PRO" in r.getMessage()+ for r in caplog.records+ )++ @pytest.mark.asyncio+ async def test_no_customer_is_safe(self):+ from backend.copilot.rate_limit import get_stripe_sweep_revert_warning++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=self._user(None),+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ ) as active_sub,+ ):+ warning = await get_stripe_sweep_revert_warning(_USER, SubscriptionTier.PRO)++ assert warning is None+ active_sub.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_active_subscription_on_the_same_tier_is_safe(self):+ from backend.copilot.rate_limit import get_stripe_sweep_revert_warning++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=self._user("cus_paying"),+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ return_value=self._sub("price_pro_yearly"),+ ),+ patch(+ "backend.data.credit.build_price_to_tier_map",+ new_callable=AsyncMock,+ return_value={"price_pro_yearly": SubscriptionTier.PRO},+ ),+ ):+ warning = await get_stripe_sweep_revert_warning(_USER, SubscriptionTier.PRO)++ assert warning is None++ @pytest.mark.asyncio+ async def test_subscription_on_an_unknown_price_stays_quiet(self):+ """A trial enrollment or unmapped price: the sweep's outcome depends on+ state this check cannot see, so no warning rather than a wrong one."""+ from backend.copilot.rate_limit import get_stripe_sweep_revert_warning++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=self._user("cus_trial"),+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ return_value=self._sub("price_trial"),+ ),+ patch(+ "backend.data.credit.build_price_to_tier_map",+ new_callable=AsyncMock,+ return_value={"price_pro_monthly": SubscriptionTier.PRO},+ ),+ ):+ warning = await get_stripe_sweep_revert_warning(_USER, SubscriptionTier.MAX)++ assert warning is None++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "tier", [SubscriptionTier.ENTERPRISE, SubscriptionTier.NO_TIER]+ )+ async def test_tiers_the_sweep_never_revokes_skip_the_lookup(self, tier):+ """ENTERPRISE is excluded from the sweep and NO_TIER is what the sweep+ would set anyway, so neither needs a Stripe round-trip."""+ from backend.copilot.rate_limit import get_stripe_sweep_revert_warning++ with patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ ) as get_user:+ warning = await get_stripe_sweep_revert_warning(_USER, tier)++ assert warning is None+ get_user.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex bb13963843..3f683cb314 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -371,10 +371,23 @@ class UserCreditBase(ABC):pass@staticmethod- async def create_billing_portal_session(user_id: str) -> str:+ async def create_billing_portal_session(user_id: str) -> str | None:+ """Return a Stripe billing-portal URL, or None when there is nothing+ to manage.++ The billing page requests this on load, so it must NOT create a Stripe+ Customer as a side effect (same contract as ``list_invoices``). A user+ with no customer has no card, invoices, or subscription to manage, and+ creating one here would make an admin-granted plan look Stripe-billed+ to the reconciliation sweep, which would then revoke it to NO_TIER.+ Checkout still provisions the customer when the user actually buys.+ """+ user = await get_user_by_id(user_id)+ if not user.stripe_customer_id:+ return Nonesession = await stripe_call(stripe.billing_portal.Session.create_async,- customer=await get_stripe_customer_id(user_id),+ customer=user.stripe_customer_id,return_url=base_url + "/settings/billing",)return session.url@@ -2517,6 +2530,11 @@ def _is_stripe_reconcilable(user: AppUser) -> bool:and are not on ENTERPRISE. Manual/admin grants are modeled as a paid tierwith no Stripe customer, or as ENTERPRISE — both are managed out-of-band andmust never be auto-revoked by Stripe reconciliation.++ That model only holds while read paths never provision a customer: anything+ the billing page requests on load (``create_billing_portal_session``,+ ``list_invoices``) must return empty for a user without one, otherwise an+ admin grant becomes reconcilable and the sweep revokes it (SECRT-2770)."""return (user.stripe_customer_id is not Nonediff --git a/autogpt_platform/backend/backend/data/credit_billing_portal_test.py b/autogpt_platform/backend/backend/data/credit_billing_portal_test.pynew file mode 100644index 0000000000..fd045871b5--- /dev/null+++ b/autogpt_platform/backend/backend/data/credit_billing_portal_test.py@@ -0,0 +1,81 @@+"""Unit tests for ``UserCreditBase.create_billing_portal_session``.++Settings > Billing requests the portal link on every page load, so the lookup+must never provision a Stripe Customer as a side effect (SECRT-2770). Doing so+made admin-granted plans look Stripe-billed to the reconciliation sweep, which+then revoked them to NO_TIER.+"""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.data.credit import UserCredit+++def _make_user(stripe_customer_id: str | None):+ user = MagicMock()+ user.stripe_customer_id = stripe_customer_id+ user.name = "Test User"+ user.email = "[email protected]"+ return user+++class TestCreateBillingPortalSession:+ @pytest.mark.asyncio+ async def test_no_customer_returns_none_without_touching_stripe(self):+ """No customer → ``None``; neither Customer.create nor a portal session+ is requested, and the user row is left alone."""+ update = AsyncMock()+ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=_make_user(None),+ ),+ patch(+ "backend.data.credit.stripe.Customer.create_async",+ new_callable=AsyncMock,+ ) as customer_create,+ patch(+ "backend.data.credit.stripe.billing_portal.Session.create_async",+ new_callable=AsyncMock,+ ) as portal_create,+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(update=update),+ ),+ ):+ url = await UserCredit.create_billing_portal_session("user-1")++ assert url is None+ customer_create.assert_not_awaited()+ portal_create.assert_not_awaited()+ update.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_existing_customer_gets_a_portal_url(self):+ session = MagicMock()+ session.url = "https://billing.stripe.com/session/abc"+ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=_make_user("cus_123"),+ ),+ patch(+ "backend.data.credit.stripe.Customer.create_async",+ new_callable=AsyncMock,+ ) as customer_create,+ patch(+ "backend.data.credit.stripe.billing_portal.Session.create_async",+ new_callable=AsyncMock,+ return_value=session,+ ) as portal_create,+ ):+ url = await UserCredit.create_billing_portal_session("user-1")++ assert url == "https://billing.stripe.com/session/abc"+ customer_create.assert_not_awaited()+ portal_create.assert_awaited_once()+ assert portal_create.await_args.kwargs["customer"] == "cus_123"diff --git a/autogpt_platform/backend/backend/data/stripe_reconciliation_integration_test.py b/autogpt_platform/backend/backend/data/stripe_reconciliation_integration_test.pynew file mode 100644index 0000000000..b767b8990c--- /dev/null+++ b/autogpt_platform/backend/backend/data/stripe_reconciliation_integration_test.py@@ -0,0 +1,134 @@+"""DB-backed regression test for SECRT-2770.++An admin grants PRO to a user with no Stripe customer, the user opens+Settings > Billing (which requests a billing-portal link), and the Stripe+reconciliation sweep runs. The grant must survive: opening the billing page+must not create a Stripe customer, so the sweep never sees the user as+Stripe-billed.+"""++import uuid+from unittest.mock import AsyncMock, MagicMock++import pytest+import pytest_mock+from prisma.enums import SubscriptionTier+from prisma.models import User++from backend.copilot.rate_limit import get_user_tier, set_user_tier+from backend.data.credit import UserCredit, _is_stripe_reconcilable+from backend.data.stripe_reconciliation import reconcile_all_stripe_tiers+from backend.data.user import get_user_by_id+from backend.util.json import SafeJson+++async def comped_user_id():+ user_id = str(uuid.uuid4())+ await User.prisma().create(+ data={+ "id": user_id,+ "email": f"comped-{user_id}@example.com",+ "topUpConfig": SafeJson({}),+ "timezone": "UTC",+ }+ )+ yield user_id+ await User.prisma().delete(where={"id": user_id})+++def _empty_stripe_pages(mocker: pytest_mock.MockFixture) -> None:+ """Stripe reports no active or trialing subscriptions at all."""++ def _list(*, status: str, limit: int, starting_after: str | None = None):+ page = MagicMock()+ page.data = []+ page.has_more = False+ return page++ mocker.patch(+ "backend.data.stripe_reconciliation.stripe.Subscription.list_async",+ side_effect=_list,+ )+ mocker.patch(+ "backend.data.stripe_reconciliation.build_price_to_tier_map",+ new_callable=AsyncMock,+ return_value={},+ )+++def _scope_sweep_to(mocker: pytest_mock.MockFixture, user_id: str) -> AsyncMock:+ """Run the sweep's real candidate query, narrowed to this test's user so+ other rows in the shared test database are left untouched.++ ``User.prisma`` is one shared classmethod, so every other call keeps+ going to the real client through the proxy; only ``find_many`` is+ narrowed, and only while the sweep runs.+ """+ real_prisma = User.prisma+ spy = AsyncMock()++ def scoped_prisma(*args, **kwargs):+ client = real_prisma(*args, **kwargs)++ async def find_many(*, where, **extra):+ return await client.find_many(where={**where, "id": user_id}, **extra)++ spy.side_effect = find_many+ proxy = MagicMock(wraps=client)+ proxy.find_many = spy+ return proxy++ mocker.patch.object(User, "prisma", side_effect=scoped_prisma)+ return spy++[email protected](loop_scope="session")+async def test_admin_grant_survives_opening_billing_and_the_sweep(+ server, mocker: pytest_mock.MockFixture, comped_user_id: str+) -> None:+ mocker.patch("backend.copilot.rate_limit.schedule_posthog_lifecycle_sync")+ mocker.patch(+ "backend.copilot.rate_limit._drift_check_background", new_callable=AsyncMock+ )+ customer_create = mocker.patch(+ "backend.data.credit.stripe.Customer.create_async", new_callable=AsyncMock+ )+ portal_create = mocker.patch(+ "backend.data.credit.stripe.billing_portal.Session.create_async",+ new_callable=AsyncMock,+ )+ mocker.patch(+ "backend.data.stripe_reconciliation.alert_tier_reconciliation_discrepancy",+ new_callable=AsyncMock,+ )+ _empty_stripe_pages(mocker)++ # 1. Admin grants PRO through Admin > Rate limits.+ await set_user_tier(comped_user_id, SubscriptionTier.PRO)+ assert await get_user_tier(comped_user_id) == SubscriptionTier.PRO++ # 2. The user opens Settings > Billing, which requests a portal link.+ assert await UserCredit.create_billing_portal_session(comped_user_id) is None+ customer_create.assert_not_awaited()+ portal_create.assert_not_awaited()+ user = await get_user_by_id(comped_user_id)+ assert user.stripe_customer_id is None+ assert not _is_stripe_reconcilable(user)++ # 3. The sweep runs with no active Stripe subscriptions anywhere.+ find_many = _scope_sweep_to(mocker, comped_user_id)+ summary = await reconcile_all_stripe_tiers()+ mocker.stopall()++ # 4. The grant is untouched: the user never became a sweep candidate.+ find_many.assert_awaited_once()+ assert find_many.await_args.kwargs["where"]["stripeCustomerId"] == {"not": None}+ assert summary.candidate_users == 0+ assert summary.downgrades == 0+ assert summary.discrepancies == []+ assert await get_user_tier(comped_user_id) == SubscriptionTier.PRO+ row = await User.prisma().find_unique(where={"id": comped_user_id})+ assert row is not None+ assert row.subscriptionTier == SubscriptionTier.PRO+ assert row.stripeCustomerId is Nonediff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsxindex bcca469887..68b306acf9 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx@@ -45,7 +45,7 @@ function tierLabel(interface Props {data: UserRateLimitResponse;onReset: (resetWeekly: boolean) => Promise<void>;- onTierChange?: (newTier: string) => Promise<void>;+ onTierChange?: (newTier: string) => Promise<string | null>;/** Full per-tier multiplier map (incl. admin-managed tiers) from the admin rate-limit endpoint. */tierMultipliers?: Record<string, number>;/** Override the outer container classes (default: bordered card). */@@ -93,7 +93,15 @@ export function RateLimitDisplay({setIsChangingTier(true);try {- await onTierChange(newTier);+ const warning = await onTierChange(newTier);+ if (warning) {+ toast({+ title: `Tier set to ${newTier}, but Stripe will revert it`,+ description: warning,+ variant: "destructive",+ });+ return;+ }toast({title: "Tier updated",description: `Changed to ${newTier} (${tierLabel(newTier as Tier, tierMultipliers)}).`,diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsxindex 0e7eb24750..100a4de032 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx@@ -9,14 +9,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { RateLimitDisplay } from "../RateLimitDisplay";import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";+const toastSpy = vi.hoisted(() => vi.fn());+vi.mock("@/components/molecules/Toast/use-toast", () => ({- useToast: () => ({ toast: vi.fn() }),+ useToast: () => ({ toast: toastSpy }),}));const mockConfirm = vi.fn();beforeEach(() => {mockConfirm.mockReset();+ toastSpy.mockClear();window.confirm = mockConfirm;});@@ -230,6 +233,59 @@ describe("RateLimitDisplay", () => {});});+ it("shows a success toast when the tier change carries no warning", async () => {+ const onTierChange = vi.fn().mockResolvedValue(null);+ mockConfirm.mockReturnValue(true);++ render(+ <RateLimitDisplay+ data={makeData({ tier: "BASIC" })}+ onReset={vi.fn()}+ onTierChange={onTierChange}+ />,+ );++ fireEvent.change(screen.getByLabelText("Subscription tier"), {+ target: { value: "PRO" },+ });++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Tier updated" }),+ );+ });+ });++ it("shows the backend warning when the Stripe sweep will revert the grant", async () => {+ const warning =+ "This user already has a Stripe customer with no active subscription.";+ const onTierChange = vi.fn().mockResolvedValue(warning);+ mockConfirm.mockReturnValue(true);++ render(+ <RateLimitDisplay+ data={makeData({ tier: "BASIC" })}+ onReset={vi.fn()}+ onTierChange={onTierChange}+ />,+ );++ fireEvent.change(screen.getByLabelText("Subscription tier"), {+ target: { value: "PRO" },+ });++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith({+ title: "Tier set to PRO, but Stripe will revert it",+ description: warning,+ variant: "destructive",+ });+ });+ expect(toastSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "Tier updated" }),+ );+ });+it("does not call onTierChange when selecting the same tier", () => {const onTierChange = vi.fn();diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsxindex 2b93ce0d9b..a52b013b5b 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx@@ -20,6 +20,7 @@ import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRimport { isKey } from "@/lib/keyboard";const toastSpy = vi.hoisted(() => vi.fn());+const tierChangeResult = vi.hoisted(() => ({ value: undefined as unknown }));vi.mock("@/components/molecules/Toast/use-toast", () => ({useToast: () => ({ toast: toastSpy }),@@ -57,7 +58,7 @@ vi.mock("../RateLimitDisplay", () => ({}: {data: UserRateLimitResponse;onReset: (rw: boolean) => Promise<void>;- onTierChange: (t: string) => Promise<void>;+ onTierChange: (t: string) => Promise<string | null>;}) => (<div data-testid="rate-limit-display"><span>{data.user_email ?? data.user_id}</span>@@ -74,7 +75,11 @@ vi.mock("../RateLimitDisplay", () => ({</button><buttononClick={() => {- onTierChange("PRO").catch(() => {});+ onTierChange("PRO")+ .then((result) => {+ tierChangeResult.value = result;+ })+ .catch(() => {});}}>mock-tier@@ -114,6 +119,7 @@ function typeAndSearch(query: string) {beforeEach(() => {toastSpy.mockClear();+ tierChangeResult.value = undefined;});afterEach(() => {@@ -375,6 +381,54 @@ describe("RateLimitManager - reset and tier change", () => {);});+ it("passes the sweep-revert warning from the set-tier response to the display", async () => {+ const warning =+ "The Stripe reconciliation sweep will revert this PRO grant to NO_TIER within 6 hours.";+ server.use(+ http.get(RATE_LIMIT_URL, () =>+ HttpResponse.json(makeRateLimit({ tier: "PRO" }), { status: 200 }),+ ),+ http.post(TIER_URL, () =>+ HttpResponse.json(+ { user_id: "user-123", tier: "PRO", warning },+ { status: 200 },+ ),+ ),+ );++ render(<RateLimitManager />);+ typeAndSearch("[email protected]");++ await screen.findByTestId("rate-limit-display");+ fireEvent.click(screen.getByText("mock-tier"));++ await waitFor(() => {+ expect(tierChangeResult.value).toBe(warning);+ });+ });++ it("resolves with no warning when the set-tier response has none", async () => {+ server.use(+ getGetV2GetUserRateLimitMockHandler200(makeRateLimit({ tier: "PRO" })),+ http.post(TIER_URL, () =>+ HttpResponse.json(+ { user_id: "user-123", tier: "PRO" },+ { status: 200 },+ ),+ ),+ );++ render(<RateLimitManager />);+ typeAndSearch("[email protected]");++ await screen.findByTestId("rate-limit-display");+ fireEvent.click(screen.getByText("mock-tier"));++ await waitFor(() => {+ expect(tierChangeResult.value).toBeNull();+ });+ });+it("does not update tier when the set-tier endpoint fails", async () => {let getCount = 0;server.use(diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.tsindex b17e8c9832..1c72b4ff5e 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts@@ -177,7 +177,7 @@ export function useRateLimitManager() {}async function handleTierChange(newTier: string) {- if (!rateLimitData) return;+ if (!rateLimitData) return null;const response = await postV2SetUserRateLimitTier({user_id: rateLimitData.user_id,@@ -188,6 +188,8 @@ export function useRateLimitManager() {throw new Error("Failed to update tier");}+ const warning = response.data.warning ?? null;+// Re-fetch rate limit data to reflect new tier-adjusted limits.try {const refreshResponse = await getV2GetUserRateLimit({@@ -200,6 +202,7 @@ export function useRateLimitManager() {// Tier was changed server-side; UI will be stale but not incorrect.// The caller's success toast is still valid — the tier change worked.}+ return warning;}return {diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex fcd45af890..0f741fbd1b 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -5799,6 +5799,7 @@"get": {"tags": ["v1", "credits"],"summary": "Manage payment methods",+ "description": "Return a Stripe billing-portal URL for the caller.\n\n``url`` is ``None`` when the user has no Stripe customer yet: this route is\nrequested on every Settings > Billing load, so it must never provision a\ncustomer as a side effect (see ``create_billing_portal_session``).","operationId": "getV1Manage payment methods","responses": {"200": {@@ -5806,7 +5807,9 @@"content": {"application/json": {"schema": {- "additionalProperties": { "type": "string" },+ "additionalProperties": {+ "anyOf": [{ "type": "string" }, { "type": "null" }]+ },"type": "object","title": "Response Getv1Manage Payment Methods"}@@ -33448,7 +33451,11 @@"UserTierResponse": {"properties": {"user_id": { "type": "string", "title": "User Id" },- "tier": { "$ref": "#/components/schemas/SubscriptionTier" }+ "tier": { "$ref": "#/components/schemas/SubscriptionTier" },+ "warning": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Warning"+ }},"type": "object","required": ["user_id", "tier"],