Skip to content

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

refactor(backend): move the subscription and Stripe routes into features/billing/subscriptions (#14477)

Reinier van der Leer0f66a1319947
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.py
index e7703f1bb4..1575c60ae9 100644
--- a/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py
@@ -96,14 +96,23 @@ def test_credit_surface_has_no_other_operations():
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.
+# The subscription and Stripe routes share the /credits prefix from their own
+# module; /credits/{transaction_key}/refund is the only wildcard among them.
@pytest.mark.parametrize(
"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/subscription",
+ "backend.api.features.billing.subscriptions.routes",
+ ),
+ (
+ "/api/credits/manage",
+ "backend.api.features.billing.subscriptions.routes",
+ ),
+ (
+ "/api/credits/stripe_webhook",
+ "backend.api.features.billing.subscriptions.routes",
+ ),
("/api/credits/transactions", "backend.api.features.billing.credits.routes"),
(
"/api/credits/{transaction_key}/refund",
diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/__init__.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py
new file mode 100644
index 0000000000..fc0bbd0bcb
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py
@@ -0,0 +1,917 @@
+import asyncio
+import logging
+from datetime import datetime, timezone
+from typing import Annotated, Literal, cast
+from urllib.parse import urlparse
+
+import stripe
+from autogpt_libs.auth import get_request_context, get_user_id, requires_user
+from autogpt_libs.auth.models import RequestContext
+from fastapi import (
+ APIRouter,
+ Depends,
+ Header,
+ HTTPException,
+ Request,
+ Response,
+ Security,
+)
+from prisma.enums import SubscriptionTier
+from pydantic import BaseModel, Field
+from typing_extensions import Optional
+
+from backend.api.features.billing.credits_rate_limit import (
+ enforce_subscription_status_rate_limit,
+)
+from backend.copilot.rate_limit import get_tier_multipliers
+from backend.data.credit import (
+ PendingChangeUnknown,
+ UserCredit,
+ cancel_stripe_subscription,
+ create_subscription_checkout,
+ get_active_subscription_period_end,
+ get_credit_model,
+ get_pending_subscription_change,
+ get_proration_credit_cents,
+ get_subscription_price_id,
+ get_user_billing_cycle,
+ handle_subscription_payment_failure,
+ handle_subscription_payment_success,
+ modify_stripe_subscription_for_tier,
+ release_pending_subscription_schedule,
+ set_subscription_tier,
+ sync_subscription_from_stripe,
+ sync_subscription_schedule_from_stripe,
+ sync_tier_from_checkout_session,
+)
+from backend.data.notifications import PassWorkEvent, PassWorkKind
+from backend.data.redis_client import get_redis_async
+from backend.data.stripe_client import stripe_call
+from backend.data.subscription_trial_billing import (
+ TRIAL_BILLING_EVENTS,
+ sync_trials_for_billing_event,
+)
+from backend.data.user import get_user_by_id
+from backend.notifications import lifecycle
+from backend.notifications.queue import queue_pass_work
+from backend.notifications.trial import notify_trial, on_trial_invoice
+from backend.util.cache import cached
+from backend.util.feature_flag import Flag, evaluate_feature_flag
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+settings = Settings()
+
+# No router-level auth: /credits/stripe_webhook is authenticated by Stripe's
+# signature, not by a user, so each route keeps its own dependency.
+router = APIRouter()
+
+
+class SubscriptionTierRequest(BaseModel):
+ tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]
+ success_url: str = ""
+ cancel_url: str = ""
+ billing_cycle: Literal["monthly", "yearly"] = "monthly"
+
+
+class SubscriptionStatusResponse(BaseModel):
+ tier: Literal["NO_TIER", "TRIAL", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]
+ monthly_cost: int # amount in cents (Stripe convention)
+ tier_costs: dict[str, int] # tier name -> monthly amount in cents
+ tier_costs_yearly: dict[str, int] = Field(
+ default_factory=dict,
+ description=(
+ "Tier → yearly amount in cents. Populated only for tiers with a"
+ " yearly Stripe price configured in LaunchDarkly. Empty for"
+ " monthly-only configurations."
+ ),
+ )
+ billing_cycle: Literal["monthly", "yearly"] = Field(
+ default="monthly",
+ description=(
+ "Billing cycle of the user's active Stripe subscription. Defaults"
+ " to ``monthly`` for users without an active sub. ``monthly_cost``"
+ " above reflects this cycle's actual price (so a yearly subscriber"
+ " sees their yearly amount, not the monthly equivalent)."
+ ),
+ )
+ tier_multipliers: dict[str, float] = Field(
+ default_factory=dict,
+ description=(
+ "Tier → rate-limit multiplier. Covers the same tiers listed in"
+ " ``tier_costs`` so the frontend can render rate-limit badges"
+ " relative to the lowest visible tier without knowing backend"
+ " defaults."
+ ),
+ )
+ proration_credit_cents: int # unused portion of current sub to convert on upgrade
+ has_active_stripe_subscription: bool = Field(
+ default=False,
+ description=(
+ "True when the user has an active/trialing Stripe subscription. The"
+ " frontend uses this to branch upgrade UX: modify-in-place + saved-card"
+ " auto-charge when True, redirect to Stripe Checkout when False."
+ ),
+ )
+ current_period_end: Optional[int] = Field(
+ default=None,
+ description=(
+ "Unix timestamp of the active subscription's current_period_end. Used"
+ " to show the date Stripe will issue the next invoice (with prorated"
+ " upgrade charges, if any). None when no active sub."
+ ),
+ )
+ pending_tier: Optional[Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]] = None
+ pending_tier_effective_at: Optional[datetime] = None
+ pending_billing_cycle: Optional[Literal["monthly", "yearly"]] = Field(
+ default=None,
+ description=(
+ "Billing cycle of the queued change, when resolvable. Set alongside"
+ " ``pending_tier`` for tier downgrades and same-tier cycle"
+ " switches (yearly→monthly). The frontend uses this to differentiate"
+ " a cycle-only schedule (``pending_tier == current tier``) from a"
+ " real tier downgrade so the UI copy can describe the actual"
+ " change. ``None`` for cancellations and unconfigured legacy prices."
+ ),
+ )
+ url: str = Field(
+ default="",
+ description=(
+ "Populated only when POST /credits/subscription starts a Stripe Checkout"
+ " Session (BASIC → paid upgrade). Empty string in all other branches —"
+ " the client redirects to this URL when non-empty."
+ ),
+ )
+
+
+def _validate_checkout_redirect_url(url: str) -> bool:
+ """Return True if `url` matches the configured frontend origin.
+
+ Prevents open-redirect: attackers must not be able to supply arbitrary
+ success_url/cancel_url that Stripe will redirect users to after checkout.
+
+ Pre-parse rejection rules (applied before urlparse):
+ - Backslashes (``\\``) are normalised differently across parsers/browsers.
+ - Control characters (U+0000–U+001F) are not valid in URLs and may confuse
+ some URL-parsing implementations.
+ """
+ # Reject characters that can confuse URL parsers before any parsing.
+ if "\\" in url:
+ return False
+ if any(ord(c) < 0x20 for c in url):
+ return False
+
+ allowed = settings.config.frontend_base_url or settings.config.platform_base_url
+ if not allowed:
+ # No configured origin — refuse to validate rather than allow arbitrary URLs.
+ return False
+ try:
+ parsed = urlparse(url)
+ allowed_parsed = urlparse(allowed)
+ except ValueError:
+ return False
+ if parsed.scheme not in ("http", "https"):
+ return False
+ # Reject ``user:pass@host`` authority tricks — ``@`` in the netloc component
+ # can trick browsers into connecting to a different host than displayed.
+ # ``@`` in query/fragment is harmless and must be allowed.
+ if "@" in parsed.netloc:
+ return False
+ return (
+ parsed.scheme == allowed_parsed.scheme
+ and parsed.netloc == allowed_parsed.netloc
+ )
+
+
+@cached(ttl_seconds=300, maxsize=32, cache_none=False)
+async def _get_stripe_price_amount(price_id: str) -> int | None:
+ """Return the unit_amount (cents) for a Stripe Price ID, cached for 5 minutes.
+
+ Returns ``None`` on transient Stripe errors. ``cache_none=False`` opts out
+ of caching the ``None`` sentinel so the next request retries Stripe instead
+ of being served a stale "no price" for the rest of the TTL window. Callers
+ should treat ``None`` as an unknown price and fall back to 0.
+
+ Stripe prices rarely change; caching avoids a ~200-600 ms Stripe round-trip on
+ every GET /credits/subscription page load and reduces quota consumption.
+ """
+ try:
+ price = await stripe_call(stripe.Price.retrieve_async, price_id)
+ return price.unit_amount or 0
+ except stripe.StripeError:
+ logger.warning(
+ "Failed to retrieve Stripe price %s — returning None (not cached)",
+ price_id,
+ )
+ return None
+
+
+ path="/credits/subscription",
+ summary="Get subscription tier, current cost, and all tier costs",
+ operation_id="getSubscriptionStatus",
+ dependencies=[
+ Security(requires_user),
+ Depends(enforce_subscription_status_rate_limit),
+ ],
+ responses={429: {"description": "Rate limit exceeded"}},
+)
+async def get_subscription_status(
+ user_id: Annotated[str, Security(get_user_id)],
+) -> SubscriptionStatusResponse:
+ user = await get_user_by_id(user_id)
+ tier = user.subscription_tier or SubscriptionTier.NO_TIER
+
+ # Tiers that *can* have a Stripe price configured (and therefore appear
+ # in the tier picker if the LD flag exposes a price-id). NO_TIER is not
+ # priceable — it's the implicit "no active subscription" state.
+ priceable_tiers = [
+ SubscriptionTier.BASIC,
+ SubscriptionTier.PRO,
+ SubscriptionTier.MAX,
+ SubscriptionTier.BUSINESS,
+ ]
+ monthly_price_ids, yearly_price_ids = await asyncio.gather(
+ asyncio.gather(
+ *[get_subscription_price_id(t, "monthly") for t in priceable_tiers]
+ ),
+ asyncio.gather(
+ *[get_subscription_price_id(t, "yearly") for t in priceable_tiers]
+ ),
+ )
+
+ async def _cost(pid: str | None) -> int:
+ return (await _get_stripe_price_amount(pid) or 0) if pid else 0
+
+ monthly_costs, yearly_costs = await asyncio.gather(
+ asyncio.gather(*[_cost(pid) for pid in monthly_price_ids]),
+ asyncio.gather(*[_cost(pid) for pid in yearly_price_ids]),
+ )
+
+ # Row visibility: include a tier if EITHER cycle is configured. Monthly
+ # cost falls back to 0 when only yearly is configured so the frontend can
+ # still render the card and surface yearly via ``tier_costs_yearly``.
+ tier_costs: dict[str, int] = {}
+ tier_costs_yearly: dict[str, int] = {}
+ for t, m_pid, y_pid, m_cost, y_cost in zip(
+ priceable_tiers,
+ monthly_price_ids,
+ yearly_price_ids,
+ monthly_costs,
+ yearly_costs,
+ ):
+ if m_pid or y_pid:
+ tier_costs[t.value] = m_cost if m_pid else 0
+ if y_pid:
+ tier_costs_yearly[t.value] = y_cost
+
+ # Expose the effective rate-limit multipliers alongside prices so the
+ # frontend can render "Nx rate limits" relative to the lowest visible
+ # tier without hard-coding backend defaults. Only emit entries for tiers
+ # that land in ``tier_costs`` — rows hidden at the price layer must stay
+ # hidden in the multiplier layer too.
+ multipliers = await get_tier_multipliers()
+ # get_tier_multipliers() keys by tier string value (see its docstring),
+ # so the lookup must use t.value — passing the enum t silently misses
+ # every tier and falls back to 1.0, ignoring LD-configured multipliers.
+ tier_multipliers: dict[str, float] = {
+ t.value: multipliers.get(t.value, 1.0)
+ for t in priceable_tiers
+ if t.value in tier_costs
+ }
+
+ user_cycle = await get_user_billing_cycle(user_id) or "monthly"
+ if user_cycle == "yearly":
+ current_monthly_cost = tier_costs_yearly.get(tier.value, 0)
+ else:
+ current_monthly_cost = tier_costs.get(tier.value, 0)
+ proration_credit, current_period_end = await asyncio.gather(
+ get_proration_credit_cents(user_id, current_monthly_cost),
+ get_active_subscription_period_end(user_id),
+ )
+
+ try:
+ pending = await get_pending_subscription_change(user_id)
+ except (stripe.StripeError, PendingChangeUnknown):
+ # Swallow Stripe-side failures (rate limits, transient network) AND
+ # PendingChangeUnknown (LaunchDarkly price-id lookup failed). Both
+ # propagate past the cache so the next request retries fresh instead
+ # of serving a stale None for the TTL window. Let real bugs (KeyError,
+ # AttributeError, etc.) propagate so they surface in Sentry.
+ logger.exception(
+ "get_subscription_status: failed to resolve pending change for user %s",
+ user_id,
+ )
+ pending = None
+
+ response = SubscriptionStatusResponse(
+ tier=tier.value,
+ monthly_cost=current_monthly_cost,
+ tier_costs=tier_costs,
+ tier_costs_yearly=tier_costs_yearly,
+ billing_cycle=user_cycle,
+ tier_multipliers=tier_multipliers,
+ proration_credit_cents=proration_credit,
+ has_active_stripe_subscription=current_period_end is not None,
+ current_period_end=current_period_end,
+ )
+ if pending is not None:
+ pending_tier_enum, pending_effective_at, pending_cycle = pending
+ if pending_tier_enum in (
+ SubscriptionTier.NO_TIER,
+ SubscriptionTier.BASIC,
+ SubscriptionTier.PRO,
+ SubscriptionTier.MAX,
+ SubscriptionTier.BUSINESS,
+ ):
+ response.pending_tier = pending_tier_enum.value
+ response.pending_tier_effective_at = pending_effective_at
+ response.pending_billing_cycle = pending_cycle
+ return response
+
+
+ path="/credits/subscription",
+ summary="Update subscription tier or start a Stripe Checkout session",
+ operation_id="updateSubscriptionTier",
+ dependencies=[Security(requires_user)],
+)
+async def update_subscription_tier(
+ request: SubscriptionTierRequest,
+ user_id: Annotated[str, Security(get_user_id)],
+ 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,
+) -> SubscriptionStatusResponse:
+ # Pydantic validates tier is one of BASIC/PRO/MAX/BUSINESS via Literal type.
+ tier = SubscriptionTier(request.tier)
+
+ # ENTERPRISE tier is admin-managed — block self-service changes from ENTERPRISE users.
+ user = await get_user_by_id(user_id)
+ if (
+ user.subscription_tier or SubscriptionTier.NO_TIER
+ ) == SubscriptionTier.ENTERPRISE:
+ raise HTTPException(
+ status_code=403,
+ detail="ENTERPRISE subscription changes must be managed by an administrator",
+ )
+
+ # Same-tier + same-cycle request = "stay on my current tier" = cancel any
+ # pending scheduled change (paid→paid downgrade or paid→BASIC cancel). This
+ # replaces the old /credits/subscription/cancel-pending route. Safe when no
+ # pending change exists: release_pending_subscription_schedule returns
+ # False and we simply return the current status.
+ #
+ # Same-tier-DIFFERENT-cycle (monthly Pro → yearly Pro, or vice versa) must
+ # fall through to modify_stripe_subscription_for_tier so Stripe swaps the
+ # price ID for the cycle the user actually requested.
+ #
+ # Gate the short-circuit on an actual active/trialing Stripe subscription:
+ # admin-granted tiers (DB tier set, no Stripe sub) must fall through to the
+ # Checkout flow so "start paying for my current tier" is not a no-op.
+ current_tier = user.subscription_tier or SubscriptionTier.NO_TIER
+ if current_tier == SubscriptionTier.TRIAL and tier != SubscriptionTier.NO_TIER:
+ raise HTTPException(
+ 409,
+ "Your accepted plan starts after your trial. Manage the trial in billing.",
+ )
+ current_cycle = await get_user_billing_cycle(user_id) or "monthly"
+ has_active_stripe_subscription = (
+ await get_active_subscription_period_end(user_id) is not None
+ )
+ if (
+ current_tier == tier
+ and current_cycle == request.billing_cycle
+ and has_active_stripe_subscription
+ ):
+ try:
+ await release_pending_subscription_schedule(user_id)
+ except stripe.StripeError as e:
+ logger.exception(
+ "Stripe error releasing pending subscription change for user %s: %s",
+ user_id,
+ e,
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to cancel the pending subscription change right now. "
+ "Please try again or contact support."
+ ),
+ )
+ return await get_subscription_status(user_id)
+
+ payment_enabled, payment_flag_authoritative = await evaluate_feature_flag(
+ Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False
+ )
+
+ target_price_id = await get_subscription_price_id(tier, request.billing_cycle)
+
+ # Cancel: target NO_TIER. Schedule Stripe cancellation at period end;
+ # cancel_at_period_end=True lets the webhook flip the DB tier. No active
+ # sub (admin-granted or never-paid) or payment disabled → DB flip.
+ # NO_TIER is never priceable, so this branch always fires for cancel
+ # requests regardless of LD config.
+ if tier == SubscriptionTier.NO_TIER:
+ if payment_enabled:
+ try:
+ had_subscription = await cancel_stripe_subscription(user_id)
+ except stripe.StripeError as e:
+ logger.exception(
+ "Stripe error cancelling subscription for user %s: %s",
+ user_id,
+ e,
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to cancel your subscription right now. "
+ "Please try again or contact support."
+ ),
+ )
+ if not had_subscription:
+ # No Stripe subscription drove this change (admin-granted or
+ # never-paid).
+ await set_subscription_tier(user_id, tier)
+ return await get_subscription_status(user_id)
+ if not payment_flag_authoritative:
+ # An unreadable flag reads False exactly like payment being off, and
+ # the DB flip below would strand a still-billing Stripe subscription.
+ logger.error(
+ f"Refusing to cancel subscription for user {user_id}: "
+ f"{Flag.ENABLE_PLATFORM_PAYMENT} could not be evaluated"
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to cancel your subscription right now. "
+ "Please try again or contact support."
+ ),
+ )
+ await set_subscription_tier(user_id, tier)
+ return await get_subscription_status(user_id)
+
+ if not payment_enabled:
+ raise HTTPException(
+ status_code=422,
+ detail=f"Subscription not available for tier {tier.value}",
+ )
+
+ # Target has no LD price — not provisionable (matches the GET hiding).
+ if target_price_id is None:
+ raise HTTPException(
+ status_code=422,
+ detail=f"Subscription not available for tier {tier.value}",
+ )
+
+ # Modify in place if there's a sub; else fall through to Checkout below.
+ try:
+ modified = await modify_stripe_subscription_for_tier(
+ user_id, tier, request.billing_cycle
+ )
+ if modified:
+ return await get_subscription_status(user_id)
+ except ValueError as e:
+ raise HTTPException(status_code=422, detail=str(e))
+ except stripe.CardError as e:
+ # Auto-charge failed under payment_behavior=error_if_incomplete: the
+ # modify was rolled back, so 402 lets the UI prompt for a new card or
+ # surface SCA. SCA codes mean the card is fine but the bank wants 3DS —
+ # different message so the user doesn't try a new card. Stripe emits
+ # ``authentication_required`` for raw PaymentIntent confirms but
+ # ``subscription_payment_intent_requires_action`` for Subscription.modify
+ # under ``error_if_incomplete``; both must map to the SCA branch.
+ if e.code in {
+ "authentication_required",
+ "subscription_payment_intent_requires_action",
+ }:
+ logger.warning(
+ "SCA required on subscription upgrade for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=402,
+ detail=(
+ "Your bank requires extra authentication for this charge."
+ " The plan was not changed; please retry from the billing"
+ " portal so you can complete authentication, or contact"
+ " support."
+ ),
+ )
+ logger.warning(
+ "Card declined on subscription upgrade for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=402,
+ detail=(
+ "Your card was declined. The plan was not changed; please"
+ " update your payment method and try again."
+ ),
+ )
+ except stripe.InvalidRequestError as e:
+ # Stripe's e.param is documented as nullable, so we match by typed
+ # field first and fall back to substring when param is absent.
+ msg_lower = (e.user_message or str(e)).lower()
+ # "No payment method" presents as InvalidRequestError (not CardError)
+ # when error_if_incomplete fires with no default PM. Stripe signals
+ # this with code=resource_missing/missing — sometimes with a typed
+ # param, sometimes without (the raw "no attached payment source"
+ # message has empty param). Map it to 402 either way.
+ if e.code in {"resource_missing", "missing"} and (
+ e.param
+ in {
+ "default_payment_method",
+ "payment_method",
+ "invoice_settings.default_payment_method",
+ }
+ or "no attached payment source" in msg_lower
+ or "default payment method" in msg_lower
+ or "no payment method" in msg_lower
+ ):
+ logger.warning(
+ "No payment method on subscription upgrade for user %s: %s",
+ user_id,
+ e,
+ )
+ raise HTTPException(
+ status_code=402,
+ detail=(
+ "No payment method on file. The plan was not changed;"
+ " please add a payment method and try again."
+ ),
+ )
+ # Stripe rejects schedule modify when phases mix currencies, e.g. the
+ # active sub was checked out in GBP but the target tier's Price is
+ # USD-only. e.param is "currency" on the schedule API but may be
+ # "phases" or absent on older error shapes — substring fallback keeps
+ # the 422 firing instead of dropping to the generic 502.
+ if e.param == "currency" or "currency" in msg_lower:
+ logger.warning(
+ "Currency mismatch on tier change for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=422,
+ detail=(
+ "Tier change unavailable for your current billing currency."
+ " Please contact support — the target tier needs to be"
+ " configured for your currency in Stripe before this"
+ " change can go through."
+ ),
+ )
+ logger.exception(
+ "Stripe error modifying subscription for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to update your subscription right now. "
+ "Please try again or contact support."
+ ),
+ )
+ except stripe.StripeError as e:
+ logger.exception(
+ "Stripe error modifying subscription for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to update your subscription right now. "
+ "Please try again or contact support."
+ ),
+ )
+
+ # No active Stripe subscription → create Stripe Checkout Session.
+ if not request.success_url or not request.cancel_url:
+ raise HTTPException(
+ status_code=422,
+ detail="success_url and cancel_url are required for paid tier upgrades",
+ )
+ # Open-redirect protection: both URLs must point to the configured frontend
+ # origin, otherwise an attacker could use our Stripe integration as a
+ # redirector to arbitrary phishing sites.
+ #
+ # Fail early with a clear 503 if the server is misconfigured (neither
+ # frontend_base_url nor platform_base_url set), so operators get an
+ # actionable error instead of the misleading "must match the platform
+ # frontend origin" 422 that _validate_checkout_redirect_url would otherwise
+ # produce when `allowed` is empty.
+ if not (settings.config.frontend_base_url or settings.config.platform_base_url):
+ logger.error(
+ "update_subscription_tier: neither frontend_base_url nor "
+ "platform_base_url is configured; cannot validate checkout redirect URLs"
+ )
+ raise HTTPException(
+ status_code=503,
+ detail=(
+ "Payment redirect URLs cannot be validated: "
+ "frontend_base_url or platform_base_url must be set on the server."
+ ),
+ )
+ if not _validate_checkout_redirect_url(
+ request.success_url
+ ) or not _validate_checkout_redirect_url(request.cancel_url):
+ raise HTTPException(
+ status_code=422,
+ detail="success_url and cancel_url must match the platform frontend origin",
+ )
+ try:
+ url = await create_subscription_checkout(
+ user_id=user_id,
+ tier=tier,
+ success_url=request.success_url,
+ cancel_url=request.cancel_url,
+ billing_cycle=request.billing_cycle,
+ datafast_visitor_id=x_datafast_visitor_id,
+ datafast_session_id=x_datafast_session_id,
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=422, detail=str(e))
+ except stripe.StripeError as e:
+ logger.exception(
+ "Stripe error creating checkout session for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to start checkout right now. "
+ "Please try again or contact support."
+ ),
+ )
+
+ status = await get_subscription_status(user_id)
+ status.url = url
+ return status
+
+
+def _stripe_event_dedup_key(event_id: str) -> str:
+ return f"stripe_webhook_event:{event_id}"
+
+
+async def _claim_stripe_event(event_id: str) -> bool:
+ """Mark a Stripe webhook event as claimed via Redis SETNX.
+
+ Returns ``True`` when the caller acquired the claim (first time we've seen
+ ``event_id``) and should proceed with handler dispatch. Returns ``False``
+ when the event was already processed in a prior delivery — Stripe retries
+ the same ``event.id`` on non-2xx responses, and we don't want downstream
+ handlers (some of which only carry per-resource idempotency) to fire twice.
+
+ Pair with ``_release_stripe_event`` in a try/except around handler dispatch:
+ on handler failure we DELete the key so Stripe's retry isn't no-op'd, but
+ a retry that arrives *during* in-flight processing still hits the live
+ claim and is deduped.
+
+ TTL of 24h comfortably exceeds Stripe's retry window. On Redis failure we
+ fall open and let processing continue — better to risk a rare duplicate
+ than to drop a real event.
+ """
+ if not event_id:
+ # Malformed event without an id — fall open so the rest of the
+ # handler can decide what to do (it'll log and 200 anyway).
+ return True
+ try:
+ redis_client = await get_redis_async()
+ claimed = await redis_client.set(
+ _stripe_event_dedup_key(event_id), "1", nx=True, ex=86400
+ )
+ return bool(claimed)
+ except Exception:
+ logger.warning(
+ "stripe_webhook: dedup claim failed for event %s; processing anyway",
+ event_id,
+ exc_info=True,
+ )
+ return True
+
+
+async def _notify_checkout_completed(session: dict) -> None:
+ """Hand the completed checkout to the lifecycle emails.
+
+ Failures here must not fail the webhook: the customer has paid, and Stripe
+ retrying the whole event would re-run `fulfill_checkout`, which grants
+ credits. But swallowing the failure lost the welcome permanently — Stripe
+ does not retry a 200, and `customer.subscription.created` deliberately does
+ not send it either.
+
+ So the work is queued rather than done here. The consumer re-reads the
+ session and subscription from Stripe and sends the welcome, with the same
+ retry-with-backoff and dead-letter queue every other notification gets.
+ Publishing is one small call that either succeeds or is logged; the Stripe
+ API round-trip and the email now sit behind a retry instead of a warning.
+ """
+ if session.get("mode") != "subscription":
+ return
+ if not session.get("subscription"):
+ return
+ session_id = session.get("id")
+ if not session_id:
+ return
+ result = await queue_pass_work(
+ PassWorkKind.WELCOME.value,
+ str(session_id),
+ PassWorkEvent(
+ kind=PassWorkKind.WELCOME,
+ user_id="",
+ scheduled_for=datetime.now(tz=timezone.utc),
+ context={"session_id": str(session_id)},
+ ).model_dump_json(),
+ )
+ if not result.success:
+ if (session.get("metadata") or {}).get("trial_enrollment_id"):
+ raise RuntimeError("Could not queue the trial welcome notice")
+ logger.warning(
+ "stripe_webhook: could not queue the welcome email for session %s: %s",
+ session_id,
+ result.message,
+ )
+
+
+async def _release_stripe_event(event_id: str) -> None:
+ """Release a previously-claimed dedup key so Stripe's retry can rerun."""
+ if not event_id:
+ return
+ try:
+ redis_client = await get_redis_async()
+ await redis_client.delete(_stripe_event_dedup_key(event_id))
+ except Exception:
+ logger.warning(
+ "stripe_webhook: dedup release failed for event %s",
+ event_id,
+ exc_info=True,
+ )
+
+
[email protected](path="/credits/stripe_webhook", summary="Handle Stripe webhooks")
+async def stripe_webhook(request: Request):
+ webhook_secret = settings.secrets.stripe_webhook_secret
+ if not webhook_secret:
+ # Guard: an empty secret allows HMAC forgery (attacker can compute a valid
+ # signature over the same empty key). Reject all webhook calls when unconfigured.
+ logger.error(
+ "stripe_webhook: STRIPE_WEBHOOK_SECRET is not configured — "
+ "rejecting request to prevent signature bypass"
+ )
+ raise HTTPException(status_code=503, detail="Webhook not configured")
+
+ # Get the raw request body
+ payload = await request.body()
+ # Get the signature header
+ sig_header = request.headers.get("stripe-signature")
+
+ try:
+ event = stripe.Webhook.construct_event(payload, sig_header, webhook_secret)
+ except ValueError:
+ # Invalid payload
+ raise HTTPException(status_code=400, detail="Invalid payload")
+ except stripe.SignatureVerificationError:
+ # Invalid signature
+ raise HTTPException(status_code=400, detail="Invalid signature")
+
+ # Defensive payload extraction. A malformed payload (missing/non-dict
+ # `data.object`, missing `id`) would otherwise raise KeyError/TypeError
+ # AFTER signature verification — which Stripe interprets as a delivery
+ # failure and retries forever, while spamming Sentry with no useful info.
+ # Acknowledge with 200 and a warning so Stripe stops retrying.
+ event_id = event.get("id", "")
+ event_type = event.get("type", "")
+
+ if event_type in TRIAL_BILLING_EVENTS:
+ # This idempotent path only reconciles current Stripe state. Do not let
+ # a claim left by a crashed delivery suppress card removal/restoration.
+ await sync_trials_for_billing_event(event_type, event.get("data"))
+ return Response(status_code=200)
+
+ # Event-level dedup: short-circuit identical re-deliveries before any
+ # handler runs. Stripe retries the same event.id on non-2xx responses, and
+ # not every downstream handler is independently idempotent.
+ if not await _claim_stripe_event(event_id):
+ logger.info(
+ "stripe_webhook: event %s (%s) already processed; skipping",
+ event_id,
+ event_type,
+ )
+ return Response(status_code=200)
+
+ event_data = event.get("data") or {}
+ data_object = event_data.get("object") if isinstance(event_data, dict) else None
+ if not isinstance(data_object, dict):
+ logger.warning(
+ "stripe_webhook: %s missing or non-dict data.object; ignoring",
+ event_type,
+ )
+ return Response(status_code=200)
+
+ # Wrap handler dispatch so a downstream failure releases the dedup claim;
+ # otherwise Stripe's retry would hit the live key and silently drop the
+ # event. Concurrent retries that arrive *during* in-flight processing
+ # still hit the live claim and are deduped.
+ try:
+ if event_type in (
+ "checkout.session.completed",
+ "checkout.session.async_payment_succeeded",
+ ):
+ session_id = data_object.get("id")
+ if not session_id:
+ logger.warning(
+ "stripe_webhook: %s missing data.object.id; ignoring", event_type
+ )
+ return Response(status_code=200)
+ await UserCredit().fulfill_checkout(session_id=session_id)
+ await sync_tier_from_checkout_session(data_object)
+ # Only `checkout.session.completed` drives the welcome email.
+ # `customer.subscription.created` fires at signup too; listening to
+ # both would double-send.
+ if event_type == "checkout.session.completed":
+ await _notify_checkout_completed(data_object)
+
+ if event_type in (
+ "customer.subscription.created",
+ "customer.subscription.updated",
+ "customer.subscription.deleted",
+ ):
+ await sync_subscription_from_stripe(data_object)
+ if event_type == "customer.subscription.updated":
+ await lifecycle.on_subscription_updated(
+ data_object, event_data.get("previous_attributes") or {}
+ )
+ elif event_type == "customer.subscription.deleted":
+ await lifecycle.on_subscription_deleted(data_object)
+
+ # `subscription_schedule.updated` is deliberately omitted: our own
+ # `SubscriptionSchedule.create` + `.modify` calls in
+ # `_schedule_downgrade_at_period_end` would fire that event right back
+ # at us and loop redundant traffic through this handler. We only care
+ # about state transitions (released / completed); phase advance to
+ # the new price is already covered by `customer.subscription.updated`.
+ if event_type in (
+ "subscription_schedule.released",
+ "subscription_schedule.completed",
+ ):
+ await sync_subscription_schedule_from_stripe(data_object)
+
+ if event_type == "invoice.payment_succeeded":
+ await handle_subscription_payment_success(data_object)
+ await on_trial_invoice(data_object, paid=True)
+
+ if event_type == "customer.subscription.trial_will_end":
+ await sync_subscription_from_stripe(data_object)
+ await notify_trial(data_object, "ending")
+
+ if event_type == "invoice.payment_failed":
+ await handle_subscription_payment_failure(data_object)
+ if not await on_trial_invoice(data_object, paid=False):
+ await lifecycle.on_payment_failed(data_object)
+
+ # New Stripe API (≥2025-04-01) split the per-payment events off the
+ # Invoice resource. data.object is an InvoicePayment, not an Invoice,
+ # so we hydrate the underlying Invoice before delegating to the
+ # existing handlers. A transient ``stripe.StripeError`` here propagates
+ # to the outer handler so the dedup claim is released and Stripe sees
+ # a 5xx + retries — swallowing it with a 200 would silently drop the
+ # event and leave the dedup key blocking the next delivery.
+ if event_type in ("invoice_payment.paid", "invoice_payment.payment_failed"):
+ invoice_id = data_object.get("invoice")
+ if invoice_id:
+ invoice = await stripe_call(stripe.Invoice.retrieve_async, invoice_id)
+ invoice_payload = cast(dict, invoice)
+ if event_type == "invoice_payment.paid":
+ await handle_subscription_payment_success(invoice_payload)
+ await on_trial_invoice(invoice_payload, paid=True)
+ else:
+ await handle_subscription_payment_failure(invoice_payload)
+ if not await on_trial_invoice(invoice_payload, paid=False):
+ await lifecycle.on_payment_failed(invoice_payload)
+
+ # `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects
+ # (Dispute/Refund). The Stripe webhook payload's `data.object` is a
+ # StripeObject (a dict subclass) carrying that runtime shape, so we
+ # cast to satisfy the type checker without changing runtime behaviour.
+ if event_type == "charge.dispute.created":
+ await UserCredit().handle_dispute(cast(stripe.Dispute, data_object))
+
+ if event_type == "refund.created" or event_type == "charge.dispute.closed":
+ await UserCredit().deduct_credits(
+ cast("stripe.Refund | stripe.Dispute", data_object)
+ )
+ except Exception:
+ # Release the dedup claim so Stripe's retry isn't no-op'd. Re-raise
+ # so the webhook returns 500 and Stripe retries (the normal contract).
+ await _release_stripe_event(event_id)
+ raise
+
+ return Response(status_code=200)
+
+
+ path="/credits/manage",
+ summary="Manage payment methods",
+ dependencies=[Security(requires_user)],
+)
+async def manage_payment_method(
+ user_id: Annotated[str, Security(get_user_id)],
+ ctx: Annotated[RequestContext, Security(get_request_context)],
+) -> 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)}
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
index 7cf91df004..bc5adb1ac4 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
@@ -11,7 +11,7 @@ from autogpt_libs.auth.jwt_utils import get_jwt_payload
from prisma.enums import SubscriptionTier
from .billing.credits_rate_limit import enforce_subscription_status_rate_limit
-from .v1 import _validate_checkout_redirect_url, v1_router
+from .billing.subscriptions.routes import _validate_checkout_redirect_url, router
TEST_USER_ID = "3e53486c-cf57-477e-ba2a-cb02dc828e1a"
TEST_FRONTEND_ORIGIN = "https://app.example.com"
@@ -26,7 +26,7 @@ def client() -> fastapi.testclient.TestClient:
previously leaking into subsequent tests.
"""
app = fastapi.FastAPI()
- app.include_router(v1_router)
+ app.include_router(router)
def override_get_jwt_payload(request: fastapi.Request) -> dict[str, str]:
return {"sub": TEST_USER_ID, "role": "user", "email": "[email protected]"}
@@ -46,10 +46,10 @@ def client() -> fastapi.testclient.TestClient:
@pytest.fixture(autouse=True)
def _configure_frontend_origin(mocker: pytest_mock.MockFixture) -> None:
"""Pin the configured frontend origin used by the open-redirect guard."""
- from backend.api.features import v1 as v1_mod
+ from backend.api.features.billing.subscriptions import routes as subscriptions_mod
mocker.patch.object(
- v1_mod.settings.config, "frontend_base_url", TEST_FRONTEND_ORIGIN
+ subscriptions_mod.settings.config, "frontend_base_url", TEST_FRONTEND_ORIGIN
)
@@ -64,7 +64,8 @@ def _stub_lifecycle_emails(mocker: pytest_mock.MockFixture) -> None:
"on_subscription_deleted",
):
mocker.patch(
- f"backend.api.features.v1.lifecycle.{handler}", new_callable=AsyncMock
+ f"backend.api.features.billing.subscriptions.routes.lifecycle.{handler}",
+ new_callable=AsyncMock,
)
mocker.patch(
"stripe.Subscription.retrieve_async",
@@ -80,7 +81,7 @@ def _stub_pending_subscription_change(mocker: pytest_mock.MockFixture) -> None:
Individual tests can override via their own mocker.patch call.
"""
mocker.patch(
- "backend.api.features.v1.get_pending_subscription_change",
+ "backend.api.features.billing.subscriptions.routes.get_pending_subscription_change",
new_callable=AsyncMock,
return_value=None,
)
@@ -122,11 +123,11 @@ def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:
return _DEFAULT_TIER_PRICES.get(tier)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=default_price_id,
)
mocker.patch(
- "backend.api.features.v1.get_proration_credit_cents",
+ "backend.api.features.billing.subscriptions.routes.get_proration_credit_cents",
new_callable=AsyncMock,
return_value=0,
)
@@ -139,14 +140,14 @@ def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:
from backend.copilot.rate_limit import _DEFAULT_TIER_MULTIPLIERS
mocker.patch(
- "backend.api.features.v1.get_tier_multipliers",
+ "backend.api.features.billing.subscriptions.routes.get_tier_multipliers",
new_callable=AsyncMock,
return_value={t.value: v for t, v in _DEFAULT_TIER_MULTIPLIERS.items()},
)
# Default billing-cycle resolver to None (treated as monthly) so existing
# tests don't have to opt into the yearly-aware code path.
mocker.patch(
- "backend.api.features.v1.get_user_billing_cycle",
+ "backend.api.features.billing.subscriptions.routes.get_user_billing_cycle",
new_callable=AsyncMock,
return_value=None,
)
@@ -154,7 +155,7 @@ def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:
# fire (they assume an active Stripe subscription). Tests that exercise
# the admin-granted "no Stripe sub" fall-through override this to None.
mocker.patch(
- "backend.api.features.v1.get_active_subscription_period_end",
+ "backend.api.features.billing.subscriptions.routes.get_active_subscription_period_end",
new_callable=AsyncMock,
return_value=1_900_000_000,
)
@@ -168,7 +169,7 @@ def _patch_payment_flag(
) -> Mock:
"""Stub the single ENABLE_PLATFORM_PAYMENT read in update_subscription_tier."""
return mocker.patch(
- "backend.api.features.v1.evaluate_feature_flag",
+ "backend.api.features.billing.subscriptions.routes.evaluate_feature_flag",
new_callable=AsyncMock,
return_value=(enabled, authoritative),
)
@@ -203,10 +204,10 @@ def test_validate_checkout_redirect_url(
mocker: pytest_mock.MockFixture,
) -> None:
"""_validate_checkout_redirect_url rejects adversarial inputs."""
- from backend.api.features import v1 as v1_mod
+ from backend.api.features.billing.subscriptions import routes as subscriptions_mod
mocker.patch.object(
- v1_mod.settings.config, "frontend_base_url", TEST_FRONTEND_ORIGIN
+ subscriptions_mod.settings.config, "frontend_base_url", TEST_FRONTEND_ORIGIN
)
assert _validate_checkout_redirect_url(url) is expected
@@ -241,20 +242,20 @@ def test_get_subscription_status_pro(
return amounts.get(price_id, 0)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=mock_price_id,
)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
side_effect=mock_stripe_price_amount,
)
mocker.patch(
- "backend.api.features.v1.get_proration_credit_cents",
+ "backend.api.features.billing.subscriptions.routes.get_proration_credit_cents",
new_callable=AsyncMock,
return_value=500,
)
@@ -289,7 +290,7 @@ def test_get_subscription_status_tier_multipliers_ld_override(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
@@ -298,7 +299,7 @@ def test_get_subscription_status_tier_multipliers_ld_override(
# Keys are tier enum string values to match get_tier_multipliers'
# documented return shape (dict[str, float]).
mocker.patch(
- "backend.api.features.v1.get_tier_multipliers",
+ "backend.api.features.billing.subscriptions.routes.get_tier_multipliers",
new_callable=AsyncMock,
return_value={
"BASIC": 1.0,
@@ -330,17 +331,17 @@ def test_get_subscription_status_defaults_to_no_tier(
mock_user.subscription_tier = None
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
new_callable=AsyncMock,
return_value=None,
)
mocker.patch(
- "backend.api.features.v1.get_proration_credit_cents",
+ "backend.api.features.billing.subscriptions.routes.get_proration_credit_cents",
new_callable=AsyncMock,
return_value=0,
)
@@ -376,20 +377,20 @@ def test_get_subscription_status_stripe_error_falls_back_to_zero(
return None
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=mock_price_id,
)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
side_effect=mock_stripe_price_amount_none,
)
mocker.patch(
- "backend.api.features.v1.get_proration_credit_cents",
+ "backend.api.features.billing.subscriptions.routes.get_proration_credit_cents",
new_callable=AsyncMock,
return_value=0,
)
@@ -413,13 +414,13 @@ def test_update_subscription_tier_no_tier_no_payment(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker, enabled=False)
mock_set_tier = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
@@ -443,17 +444,17 @@ def test_update_subscription_tier_no_tier_unreadable_flag_keeps_tier(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker, enabled=False, authoritative=False)
mock_set_tier = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
mock_cancel = mocker.patch(
- "backend.api.features.v1.cancel_stripe_subscription",
+ "backend.api.features.billing.subscriptions.routes.cancel_stripe_subscription",
new_callable=AsyncMock,
)
@@ -474,7 +475,7 @@ def test_update_subscription_tier_paid_beta_user(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
@@ -495,13 +496,13 @@ def test_update_subscription_tier_paid_requires_urls(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
@@ -524,13 +525,13 @@ def test_update_subscription_tier_currency_mismatch_returns_422(
mock_user.subscription_tier = SubscriptionTier.MAX
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
side_effect=stripe.InvalidRequestError(
"The price specified only supports `usd`. This doesn't match the"
" expected currency: `gbp`.",
@@ -565,13 +566,13 @@ def test_update_subscription_tier_non_currency_invalid_request_returns_502(
mock_user.subscription_tier = SubscriptionTier.MAX
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
side_effect=stripe.InvalidRequestError(
"No such price: 'price_does_not_exist'",
param="items[0][price]",
@@ -600,18 +601,18 @@ def test_update_subscription_tier_creates_checkout(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
return_value="https://checkout.stripe.com/pay/cs_test_abc",
)
@@ -638,18 +639,18 @@ def test_update_subscription_tier_forwards_datafast_headers(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
mock_checkout = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
return_value="https://checkout.stripe.com/pay/cs_test_abc",
)
@@ -683,18 +684,18 @@ def test_update_subscription_tier_forwards_yearly_billing_cycle(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=True,
)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
new_callable=AsyncMock,
return_value=1999,
)
@@ -705,7 +706,7 @@ def test_update_subscription_tier_forwards_yearly_billing_cycle(
return "price_pro_yearly"
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_lookup,
)
@@ -734,13 +735,13 @@ def test_update_subscription_tier_yearly_unconfigured_returns_422(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
new_callable=AsyncMock,
return_value=1999,
)
@@ -751,11 +752,11 @@ def test_update_subscription_tier_yearly_unconfigured_returns_422(
return "price_pro_monthly"
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_lookup,
)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
)
@@ -782,13 +783,13 @@ def test_update_subscription_tier_creates_checkout_with_yearly_billing(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
new_callable=AsyncMock,
return_value=1999,
)
@@ -797,16 +798,16 @@ def test_update_subscription_tier_creates_checkout_with_yearly_billing(
return "price_pro_yearly"
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_lookup,
)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
return_value="https://checkout.stripe.com/pay/cs_test_yearly",
)
@@ -837,18 +838,18 @@ def test_update_subscription_tier_rejects_open_redirect(
mock_user.subscription_tier = SubscriptionTier.BASIC
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
@@ -874,12 +875,12 @@ def test_update_subscription_tier_enterprise_blocked(
mock_user.subscription_tier = SubscriptionTier.ENTERPRISE
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
set_tier_mock = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
@@ -912,17 +913,17 @@ def test_update_subscription_tier_same_tier_releases_pending_change(
mock_user.subscription_tier = SubscriptionTier.BUSINESS
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
release_mock = mocker.patch(
- "backend.api.features.v1.release_pending_subscription_schedule",
+ "backend.api.features.billing.subscriptions.routes.release_pending_subscription_schedule",
new_callable=AsyncMock,
return_value=True,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
feature_mock = _patch_payment_flag(mocker)
@@ -955,17 +956,17 @@ def test_update_subscription_tier_same_tier_no_pending_change_returns_status(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
release_mock = mocker.patch(
- "backend.api.features.v1.release_pending_subscription_schedule",
+ "backend.api.features.billing.subscriptions.routes.release_pending_subscription_schedule",
new_callable=AsyncMock,
return_value=False,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
@@ -1001,12 +1002,12 @@ def test_update_subscription_tier_same_tier_stripe_error_returns_502(
mock_user.subscription_tier = SubscriptionTier.BUSINESS
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.release_pending_subscription_schedule",
+ "backend.api.features.billing.subscriptions.routes.release_pending_subscription_schedule",
side_effect=stripe.StripeError("network"),
)
@@ -1036,15 +1037,15 @@ def test_update_subscription_tier_no_tier_with_payment_schedules_cancel_and_does
mock_user.subscription_tier = SubscriptionTier.PRO
mock_cancel = mocker.patch(
- "backend.api.features.v1.cancel_stripe_subscription",
+ "backend.api.features.billing.subscriptions.routes.cancel_stripe_subscription",
new_callable=AsyncMock,
)
mock_set_tier = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
@@ -1066,13 +1067,13 @@ def test_update_subscription_tier_no_tier_cancel_failure_returns_502(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.cancel_stripe_subscription",
+ "backend.api.features.billing.subscriptions.routes.cancel_stripe_subscription",
side_effect=stripe.StripeError(
"You did not provide an API key — internal detail that must not leak"
),
)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
@@ -1098,7 +1099,7 @@ def test_stripe_webhook_unconfigured_secret_returns_503(
when the secret is unconfigured rather than proceeding with signature verification.
"""
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="",
)
response = client.post(
@@ -1127,15 +1128,15 @@ def test_stripe_webhook_dispatches_subscription_events(
# Ensure the webhook secret guard passes (non-empty secret required).
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1.stripe.Webhook.construct_event",
+ "backend.api.features.billing.subscriptions.routes.stripe.Webhook.construct_event",
return_value=event,
)
sync_mock = mocker.patch(
- "backend.api.features.v1.sync_subscription_from_stripe",
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_from_stripe",
new_callable=AsyncMock,
)
@@ -1165,15 +1166,15 @@ def test_stripe_webhook_dispatches_invoice_payment_failed(
}
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1.stripe.Webhook.construct_event",
+ "backend.api.features.billing.subscriptions.routes.stripe.Webhook.construct_event",
return_value=event,
)
failure_mock = mocker.patch(
- "backend.api.features.v1.handle_subscription_payment_failure",
+ "backend.api.features.billing.subscriptions.routes.handle_subscription_payment_failure",
new_callable=AsyncMock,
)
@@ -1204,22 +1205,22 @@ def test_update_subscription_tier_paid_to_paid_modifies_subscription(
}.get(tier)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_id_with_business,
)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=True,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
@@ -1249,18 +1250,18 @@ def test_update_subscription_tier_max_checkout(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=True,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
@@ -1294,22 +1295,22 @@ def test_update_subscription_tier_no_active_sub_falls_through_to_checkout(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
set_tier_mock = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
return_value="https://checkout.stripe.com/pay/cs_test_no_sub",
)
@@ -1351,26 +1352,26 @@ def test_update_subscription_tier_priced_basic_no_sub_falls_through_to_checkout(
}.get(tier)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=mock_price_id,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
set_tier_mock = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
return_value="https://checkout.stripe.com/pay/cs_test_priced_basic",
)
@@ -1416,21 +1417,21 @@ def test_update_subscription_tier_target_without_ld_price_returns_422(
return None # Neither BASIC nor PRO have an LD price.
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=mock_price_id,
)
_patch_payment_flag(mocker)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
)
@@ -1464,13 +1465,13 @@ def test_update_subscription_tier_pro_to_max_card_declined_returns_402(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
side_effect=stripe.CardError(
"Your card was declined.", param="card", code="card_declined"
@@ -1502,13 +1503,13 @@ def test_update_subscription_tier_pro_to_max_authentication_required_returns_402
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
side_effect=stripe.CardError(
"Your card was declined.",
@@ -1547,13 +1548,13 @@ def test_update_subscription_tier_pro_to_max_subscription_payment_intent_require
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
side_effect=stripe.CardError(
"Payment for this subscription requires additional user action"
@@ -1589,13 +1590,13 @@ def test_update_subscription_tier_pro_to_max_no_payment_method_returns_402(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
side_effect=stripe.InvalidRequestError(
"This customer has no attached payment source or default payment"
@@ -1637,17 +1638,17 @@ def test_update_subscription_tier_paid_to_paid_stripe_error_returns_502(
}.get(tier)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_id_with_business,
)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
side_effect=stripe.StripeError("connection error"),
)
@@ -1679,19 +1680,19 @@ def test_update_subscription_tier_no_tier_no_stripe_subscription(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
# Simulate no active Stripe subscriptions — returns False
cancel_mock = mocker.patch(
- "backend.api.features.v1.cancel_stripe_subscription",
+ "backend.api.features.billing.subscriptions.routes.cancel_stripe_subscription",
new_callable=AsyncMock,
return_value=False,
)
set_tier_mock = mocker.patch(
- "backend.api.features.v1.set_subscription_tier",
+ "backend.api.features.billing.subscriptions.routes.set_subscription_tier",
new_callable=AsyncMock,
)
@@ -1722,21 +1723,21 @@ def test_get_subscription_status_includes_pending_tier(
return None
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=mock_price_id,
)
mocker.patch(
- "backend.api.features.v1.get_proration_credit_cents",
+ "backend.api.features.billing.subscriptions.routes.get_proration_credit_cents",
new_callable=AsyncMock,
return_value=0,
)
mocker.patch(
- "backend.api.features.v1.get_pending_subscription_change",
+ "backend.api.features.billing.subscriptions.routes.get_pending_subscription_change",
new_callable=AsyncMock,
return_value=(SubscriptionTier.PRO, effective_at, "monthly"),
)
@@ -1759,22 +1760,22 @@ def test_get_subscription_status_no_pending_tier(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
new_callable=AsyncMock,
return_value=None,
)
mocker.patch(
- "backend.api.features.v1.get_proration_credit_cents",
+ "backend.api.features.billing.subscriptions.routes.get_proration_credit_cents",
new_callable=AsyncMock,
return_value=0,
)
mocker.patch(
- "backend.api.features.v1.get_pending_subscription_change",
+ "backend.api.features.billing.subscriptions.routes.get_pending_subscription_change",
new_callable=AsyncMock,
return_value=None,
)
@@ -1804,22 +1805,22 @@ def test_update_subscription_tier_downgrade_paid_to_paid_schedules(
}.get(tier)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_id_with_business,
)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=True,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
)
@@ -1849,15 +1850,15 @@ def test_stripe_webhook_dispatches_subscription_schedule_released(
"data": {"object": schedule_obj},
}
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1.stripe.Webhook.construct_event",
+ "backend.api.features.billing.subscriptions.routes.stripe.Webhook.construct_event",
return_value=event,
)
sync_mock = mocker.patch(
- "backend.api.features.v1.sync_subscription_schedule_from_stripe",
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_schedule_from_stripe",
new_callable=AsyncMock,
)
@@ -1887,15 +1888,15 @@ def test_stripe_webhook_ignores_subscription_schedule_updated(
"data": {"object": schedule_obj},
}
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1.stripe.Webhook.construct_event",
+ "backend.api.features.billing.subscriptions.routes.stripe.Webhook.construct_event",
return_value=event,
)
sync_mock = mocker.patch(
- "backend.api.features.v1.sync_subscription_schedule_from_stripe",
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_schedule_from_stripe",
new_callable=AsyncMock,
)
@@ -1941,20 +1942,20 @@ def test_get_subscription_status_yearly_only_tier_visible(
return amounts.get(price_id, 0)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_lookup,
)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
side_effect=stripe_amount,
)
mocker.patch(
- "backend.api.features.v1.get_user_billing_cycle",
+ "backend.api.features.billing.subscriptions.routes.get_user_billing_cycle",
new_callable=AsyncMock,
return_value="yearly",
)
@@ -2003,20 +2004,20 @@ def test_get_subscription_status_yearly_user_both_cycles_uses_yearly_cost(
return amounts.get(price_id, 0)
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_lookup,
)
mocker.patch(
- "backend.api.features.v1._get_stripe_price_amount",
+ "backend.api.features.billing.subscriptions.routes._get_stripe_price_amount",
side_effect=stripe_amount,
)
mocker.patch(
- "backend.api.features.v1.get_user_billing_cycle",
+ "backend.api.features.billing.subscriptions.routes.get_user_billing_cycle",
new_callable=AsyncMock,
return_value="yearly",
)
@@ -2054,27 +2055,27 @@ def test_update_subscription_tier_same_tier_cycle_change_routes_to_modify(
return None
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
_patch_payment_flag(mocker)
mocker.patch(
- "backend.api.features.v1.get_subscription_price_id",
+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",
side_effect=price_lookup,
)
# User is currently on monthly Pro.
mocker.patch(
- "backend.api.features.v1.get_user_billing_cycle",
+ "backend.api.features.billing.subscriptions.routes.get_user_billing_cycle",
new_callable=AsyncMock,
return_value="monthly",
)
release_mock = mocker.patch(
- "backend.api.features.v1.release_pending_subscription_schedule",
+ "backend.api.features.billing.subscriptions.routes.release_pending_subscription_schedule",
new_callable=AsyncMock,
)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=True,
)
@@ -2104,22 +2105,22 @@ def test_update_subscription_tier_same_tier_same_cycle_still_releases_pending(
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
mocker.patch(
- "backend.api.features.v1.get_user_billing_cycle",
+ "backend.api.features.billing.subscriptions.routes.get_user_billing_cycle",
new_callable=AsyncMock,
return_value="yearly",
)
release_mock = mocker.patch(
- "backend.api.features.v1.release_pending_subscription_schedule",
+ "backend.api.features.billing.subscriptions.routes.release_pending_subscription_schedule",
new_callable=AsyncMock,
return_value=True,
)
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
)
@@ -2151,19 +2152,19 @@ def test_update_subscription_tier_same_tier_no_stripe_sub_falls_through_to_check
mock_user.subscription_tier = SubscriptionTier.PRO
mocker.patch(
- "backend.api.features.v1.get_user_by_id",
+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
# No active Stripe subscription — period_end is None.
mocker.patch(
- "backend.api.features.v1.get_active_subscription_period_end",
+ "backend.api.features.billing.subscriptions.routes.get_active_subscription_period_end",
new_callable=AsyncMock,
return_value=None,
)
_patch_payment_flag(mocker)
release_mock = mocker.patch(
- "backend.api.features.v1.release_pending_subscription_schedule",
+ "backend.api.features.billing.subscriptions.routes.release_pending_subscription_schedule",
new_callable=AsyncMock,
)
# Admin-granted user has no active Stripe sub, so the modify path returns
@@ -2171,12 +2172,12 @@ def test_update_subscription_tier_same_tier_no_stripe_sub_falls_through_to_check
# real backend.data.credit.modify_stripe_subscription_for_tier (which
# would try to read from Prisma + call Stripe).
modify_mock = mocker.patch(
- "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",
new_callable=AsyncMock,
return_value=False,
)
checkout_mock = mocker.patch(
- "backend.api.features.v1.create_subscription_checkout",
+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
new_callable=AsyncMock,
return_value="https://checkout.example.com/sess_admingranted",
)
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index b1f0220312..2454e4707b 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -4,11 +4,9 @@ import logging
import time
from collections import defaultdict
from datetime import datetime, timezone
-from typing import Annotated, Literal, cast, get_args
-from urllib.parse import urlparse
+from typing import Annotated, get_args
import pydantic
-import stripe
from autogpt_libs.auth import get_request_context, get_user_id, requires_user
from autogpt_libs.auth.jwt_utils import get_jwt_payload
from autogpt_libs.auth.models import RequestContext
@@ -17,59 +15,28 @@ from fastapi import (
Body,
Depends,
File,
- Header,
HTTPException,
Query,
- Request,
Response,
Security,
UploadFile,
)
from fastapi.concurrency import run_in_threadpool
-from prisma.enums import BriefingFrequency, SubscriptionTier
-from pydantic import BaseModel, Field
+from prisma.enums import BriefingFrequency
+from pydantic import BaseModel
from starlette.status import HTTP_402_PAYMENT_REQUIRED
-from typing_extensions import Optional
-from backend.api.features.billing.credits_rate_limit import (
- enforce_subscription_status_rate_limit,
-)
from backend.api.model import (
TimezoneResponse,
UpdateTimezoneRequest,
UploadFileResponse,
)
from backend.blocks import get_block, get_blocks
-from backend.copilot.rate_limit import enforce_payment_paywall, get_tier_multipliers
+from backend.copilot.rate_limit import enforce_payment_paywall
from backend.data.block import BlockInput, CompletedBlockOutput
-from backend.data.credit import (
- PendingChangeUnknown,
- UserCredit,
- cancel_stripe_subscription,
- create_subscription_checkout,
- get_active_subscription_period_end,
- get_credit_model,
- get_pending_subscription_change,
- get_proration_credit_cents,
- get_subscription_price_id,
- get_user_billing_cycle,
- handle_subscription_payment_failure,
- handle_subscription_payment_success,
- modify_stripe_subscription_for_tier,
- release_pending_subscription_schedule,
- set_subscription_tier,
- sync_subscription_from_stripe,
- sync_subscription_schedule_from_stripe,
- sync_tier_from_checkout_session,
-)
from backend.data.execution import ExecutionContext
from backend.data.model import UserOnboarding
-from backend.data.notifications import (
- NotificationPreference,
- NotificationPreferenceDTO,
- PassWorkEvent,
- PassWorkKind,
-)
+from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
from backend.data.onboarding import (
FrontendOnboardingStep,
OnboardingStep,
@@ -81,12 +48,6 @@ from backend.data.onboarding import (
reset_user_onboarding,
update_user_onboarding,
)
-from backend.data.redis_client import get_redis_async
-from backend.data.stripe_client import stripe_call
-from backend.data.subscription_trial_billing import (
- TRIAL_BILLING_EVENTS,
- sync_trials_for_billing_event,
-)
from backend.data.tally import extract_business_understanding
from backend.data.understanding import (
BusinessUnderstandingInput,
@@ -104,13 +65,9 @@ from backend.data.user import (
)
from backend.executor import utils as execution_utils
from backend.monitoring.instrumentation import record_block_execution
-from backend.notifications import lifecycle
-from backend.notifications.queue import queue_pass_work
-from backend.notifications.trial import notify_trial, on_trial_invoice
from backend.util.cache import cached
from backend.util.cloud_storage import get_cloud_storage_handler
from backend.util.exceptions import InsufficientBalanceError
-from backend.util.feature_flag import Flag, evaluate_feature_flag
from backend.util.json import dumps
from backend.util.settings import Settings
from backend.util.timezone_utils import get_user_timezone_or_utc
@@ -655,863 +612,3 @@ async def upload_file(
content_type=content_type,
expires_in_hours=expiration_hours,
)
-
-
-########################################################
-##################### Credits ##########################
-########################################################
-
-
-class SubscriptionTierRequest(BaseModel):
- tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]
- success_url: str = ""
- cancel_url: str = ""
- billing_cycle: Literal["monthly", "yearly"] = "monthly"
-
-
-class SubscriptionStatusResponse(BaseModel):
- tier: Literal["NO_TIER", "TRIAL", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]
- monthly_cost: int # amount in cents (Stripe convention)
- tier_costs: dict[str, int] # tier name -> monthly amount in cents
- tier_costs_yearly: dict[str, int] = Field(
- default_factory=dict,
- description=(
- "Tier → yearly amount in cents. Populated only for tiers with a"
- " yearly Stripe price configured in LaunchDarkly. Empty for"
- " monthly-only configurations."
- ),
- )
- billing_cycle: Literal["monthly", "yearly"] = Field(
- default="monthly",
- description=(
- "Billing cycle of the user's active Stripe subscription. Defaults"
- " to ``monthly`` for users without an active sub. ``monthly_cost``"
- " above reflects this cycle's actual price (so a yearly subscriber"
- " sees their yearly amount, not the monthly equivalent)."
- ),
- )
- tier_multipliers: dict[str, float] = Field(
- default_factory=dict,
- description=(
- "Tier → rate-limit multiplier. Covers the same tiers listed in"
- " ``tier_costs`` so the frontend can render rate-limit badges"
- " relative to the lowest visible tier without knowing backend"
- " defaults."
- ),
- )
- proration_credit_cents: int # unused portion of current sub to convert on upgrade
- has_active_stripe_subscription: bool = Field(
- default=False,
- description=(
- "True when the user has an active/trialing Stripe subscription. The"
- " frontend uses this to branch upgrade UX: modify-in-place + saved-card"
- " auto-charge when True, redirect to Stripe Checkout when False."
- ),
- )
- current_period_end: Optional[int] = Field(
- default=None,
- description=(
- "Unix timestamp of the active subscription's current_period_end. Used"
- " to show the date Stripe will issue the next invoice (with prorated"
- " upgrade charges, if any). None when no active sub."
- ),
- )
- pending_tier: Optional[Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]] = None
- pending_tier_effective_at: Optional[datetime] = None
- pending_billing_cycle: Optional[Literal["monthly", "yearly"]] = Field(
- default=None,
- description=(
- "Billing cycle of the queued change, when resolvable. Set alongside"
- " ``pending_tier`` for tier downgrades and same-tier cycle"
- " switches (yearly→monthly). The frontend uses this to differentiate"
- " a cycle-only schedule (``pending_tier == current tier``) from a"
- " real tier downgrade so the UI copy can describe the actual"
- " change. ``None`` for cancellations and unconfigured legacy prices."
- ),
- )
- url: str = Field(
- default="",
- description=(
- "Populated only when POST /credits/subscription starts a Stripe Checkout"
- " Session (BASIC → paid upgrade). Empty string in all other branches —"
- " the client redirects to this URL when non-empty."
- ),
- )
-
-
-def _validate_checkout_redirect_url(url: str) -> bool:
- """Return True if `url` matches the configured frontend origin.
-
- Prevents open-redirect: attackers must not be able to supply arbitrary
- success_url/cancel_url that Stripe will redirect users to after checkout.
-
- Pre-parse rejection rules (applied before urlparse):
- - Backslashes (``\\``) are normalised differently across parsers/browsers.
- - Control characters (U+0000–U+001F) are not valid in URLs and may confuse
- some URL-parsing implementations.
- """
- # Reject characters that can confuse URL parsers before any parsing.
- if "\\" in url:
- return False
- if any(ord(c) < 0x20 for c in url):
- return False
-
- allowed = settings.config.frontend_base_url or settings.config.platform_base_url
- if not allowed:
- # No configured origin — refuse to validate rather than allow arbitrary URLs.
- return False
- try:
- parsed = urlparse(url)
- allowed_parsed = urlparse(allowed)
- except ValueError:
- return False
- if parsed.scheme not in ("http", "https"):
- return False
- # Reject ``user:pass@host`` authority tricks — ``@`` in the netloc component
- # can trick browsers into connecting to a different host than displayed.
- # ``@`` in query/fragment is harmless and must be allowed.
- if "@" in parsed.netloc:
- return False
- return (
- parsed.scheme == allowed_parsed.scheme
- and parsed.netloc == allowed_parsed.netloc
- )
-
-
-@cached(ttl_seconds=300, maxsize=32, cache_none=False)
-async def _get_stripe_price_amount(price_id: str) -> int | None:
- """Return the unit_amount (cents) for a Stripe Price ID, cached for 5 minutes.
-
- Returns ``None`` on transient Stripe errors. ``cache_none=False`` opts out
- of caching the ``None`` sentinel so the next request retries Stripe instead
- of being served a stale "no price" for the rest of the TTL window. Callers
- should treat ``None`` as an unknown price and fall back to 0.
-
- Stripe prices rarely change; caching avoids a ~200-600 ms Stripe round-trip on
- every GET /credits/subscription page load and reduces quota consumption.
- """
- try:
- price = await stripe_call(stripe.Price.retrieve_async, price_id)
- return price.unit_amount or 0
- except stripe.StripeError:
- logger.warning(
- "Failed to retrieve Stripe price %s — returning None (not cached)",
- price_id,
- )
- return None
-
-
-@v1_router.get(
- path="/credits/subscription",
- summary="Get subscription tier, current cost, and all tier costs",
- operation_id="getSubscriptionStatus",
- tags=["credits"],
- dependencies=[
- Security(requires_user),
- Depends(enforce_subscription_status_rate_limit),
- ],
- responses={429: {"description": "Rate limit exceeded"}},
-)
-async def get_subscription_status(
- user_id: Annotated[str, Security(get_user_id)],
-) -> SubscriptionStatusResponse:
- user = await get_user_by_id(user_id)
- tier = user.subscription_tier or SubscriptionTier.NO_TIER
-
- # Tiers that *can* have a Stripe price configured (and therefore appear
- # in the tier picker if the LD flag exposes a price-id). NO_TIER is not
- # priceable — it's the implicit "no active subscription" state.
- priceable_tiers = [
- SubscriptionTier.BASIC,
- SubscriptionTier.PRO,
- SubscriptionTier.MAX,
- SubscriptionTier.BUSINESS,
- ]
- monthly_price_ids, yearly_price_ids = await asyncio.gather(
- asyncio.gather(
- *[get_subscription_price_id(t, "monthly") for t in priceable_tiers]
- ),
- asyncio.gather(
- *[get_subscription_price_id(t, "yearly") for t in priceable_tiers]
- ),
- )
-
- async def _cost(pid: str | None) -> int:
- return (await _get_stripe_price_amount(pid) or 0) if pid else 0
-
- monthly_costs, yearly_costs = await asyncio.gather(
- asyncio.gather(*[_cost(pid) for pid in monthly_price_ids]),
- asyncio.gather(*[_cost(pid) for pid in yearly_price_ids]),
- )
-
- # Row visibility: include a tier if EITHER cycle is configured. Monthly
- # cost falls back to 0 when only yearly is configured so the frontend can
- # still render the card and surface yearly via ``tier_costs_yearly``.
- tier_costs: dict[str, int] = {}
- tier_costs_yearly: dict[str, int] = {}
- for t, m_pid, y_pid, m_cost, y_cost in zip(
- priceable_tiers,
- monthly_price_ids,
- yearly_price_ids,
- monthly_costs,
- yearly_costs,
- ):
- if m_pid or y_pid:
- tier_costs[t.value] = m_cost if m_pid else 0
- if y_pid:
- tier_costs_yearly[t.value] = y_cost
-
- # Expose the effective rate-limit multipliers alongside prices so the
- # frontend can render "Nx rate limits" relative to the lowest visible
- # tier without hard-coding backend defaults. Only emit entries for tiers
- # that land in ``tier_costs`` — rows hidden at the price layer must stay
- # hidden in the multiplier layer too.
- multipliers = await get_tier_multipliers()
- # get_tier_multipliers() keys by tier string value (see its docstring),
- # so the lookup must use t.value — passing the enum t silently misses
- # every tier and falls back to 1.0, ignoring LD-configured multipliers.
- tier_multipliers: dict[str, float] = {
- t.value: multipliers.get(t.value, 1.0)
- for t in priceable_tiers
- if t.value in tier_costs
- }
-
- user_cycle = await get_user_billing_cycle(user_id) or "monthly"
- if user_cycle == "yearly":
- current_monthly_cost = tier_costs_yearly.get(tier.value, 0)
- else:
- current_monthly_cost = tier_costs.get(tier.value, 0)
- proration_credit, current_period_end = await asyncio.gather(
- get_proration_credit_cents(user_id, current_monthly_cost),
- get_active_subscription_period_end(user_id),
- )
-
- try:
- pending = await get_pending_subscription_change(user_id)
- except (stripe.StripeError, PendingChangeUnknown):
- # Swallow Stripe-side failures (rate limits, transient network) AND
- # PendingChangeUnknown (LaunchDarkly price-id lookup failed). Both
- # propagate past the cache so the next request retries fresh instead
- # of serving a stale None for the TTL window. Let real bugs (KeyError,
- # AttributeError, etc.) propagate so they surface in Sentry.
- logger.exception(
- "get_subscription_status: failed to resolve pending change for user %s",
- user_id,
- )
- pending = None
-
- response = SubscriptionStatusResponse(
- tier=tier.value,
- monthly_cost=current_monthly_cost,
- tier_costs=tier_costs,
- tier_costs_yearly=tier_costs_yearly,
- billing_cycle=user_cycle,
- tier_multipliers=tier_multipliers,
- proration_credit_cents=proration_credit,
- has_active_stripe_subscription=current_period_end is not None,
- current_period_end=current_period_end,
- )
- if pending is not None:
- pending_tier_enum, pending_effective_at, pending_cycle = pending
- if pending_tier_enum in (
- SubscriptionTier.NO_TIER,
- SubscriptionTier.BASIC,
- SubscriptionTier.PRO,
- SubscriptionTier.MAX,
- SubscriptionTier.BUSINESS,
- ):
- response.pending_tier = pending_tier_enum.value
- response.pending_tier_effective_at = pending_effective_at
- response.pending_billing_cycle = pending_cycle
- return response
-
-
-@v1_router.post(
- path="/credits/subscription",
- summary="Update subscription tier or start a Stripe Checkout session",
- operation_id="updateSubscriptionTier",
- tags=["credits"],
- dependencies=[Security(requires_user)],
-)
-async def update_subscription_tier(
- request: SubscriptionTierRequest,
- user_id: Annotated[str, Security(get_user_id)],
- 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,
-) -> SubscriptionStatusResponse:
- # Pydantic validates tier is one of BASIC/PRO/MAX/BUSINESS via Literal type.
- tier = SubscriptionTier(request.tier)
-
- # ENTERPRISE tier is admin-managed — block self-service changes from ENTERPRISE users.
- user = await get_user_by_id(user_id)
- if (
- user.subscription_tier or SubscriptionTier.NO_TIER
- ) == SubscriptionTier.ENTERPRISE:
- raise HTTPException(
- status_code=403,
- detail="ENTERPRISE subscription changes must be managed by an administrator",
- )
-
- # Same-tier + same-cycle request = "stay on my current tier" = cancel any
- # pending scheduled change (paid→paid downgrade or paid→BASIC cancel). This
- # replaces the old /credits/subscription/cancel-pending route. Safe when no
- # pending change exists: release_pending_subscription_schedule returns
- # False and we simply return the current status.
- #
- # Same-tier-DIFFERENT-cycle (monthly Pro → yearly Pro, or vice versa) must
- # fall through to modify_stripe_subscription_for_tier so Stripe swaps the
- # price ID for the cycle the user actually requested.
- #
- # Gate the short-circuit on an actual active/trialing Stripe subscription:
- # admin-granted tiers (DB tier set, no Stripe sub) must fall through to the
- # Checkout flow so "start paying for my current tier" is not a no-op.
- current_tier = user.subscription_tier or SubscriptionTier.NO_TIER
- if current_tier == SubscriptionTier.TRIAL and tier != SubscriptionTier.NO_TIER:
- raise HTTPException(
- 409,
- "Your accepted plan starts after your trial. Manage the trial in billing.",
- )
- current_cycle = await get_user_billing_cycle(user_id) or "monthly"
- has_active_stripe_subscription = (
- await get_active_subscription_period_end(user_id) is not None
- )
- if (
- current_tier == tier
- and current_cycle == request.billing_cycle
- and has_active_stripe_subscription
- ):
- try:
- await release_pending_subscription_schedule(user_id)
- except stripe.StripeError as e:
- logger.exception(
- "Stripe error releasing pending subscription change for user %s: %s",
- user_id,
- e,
- )
- raise HTTPException(
- status_code=502,
- detail=(
- "Unable to cancel the pending subscription change right now. "
- "Please try again or contact support."
- ),
- )
- return await get_subscription_status(user_id)
-
- payment_enabled, payment_flag_authoritative = await evaluate_feature_flag(
- Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False
- )
-
- target_price_id = await get_subscription_price_id(tier, request.billing_cycle)
-
- # Cancel: target NO_TIER. Schedule Stripe cancellation at period end;
- # cancel_at_period_end=True lets the webhook flip the DB tier. No active
- # sub (admin-granted or never-paid) or payment disabled → DB flip.
- # NO_TIER is never priceable, so this branch always fires for cancel
- # requests regardless of LD config.
- if tier == SubscriptionTier.NO_TIER:
- if payment_enabled:
- try:
- had_subscription = await cancel_stripe_subscription(user_id)
- except stripe.StripeError as e:
- logger.exception(
- "Stripe error cancelling subscription for user %s: %s",
- user_id,
- e,
- )
- raise HTTPException(
- status_code=502,
- detail=(
- "Unable to cancel your subscription right now. "
- "Please try again or contact support."
- ),
- )
- if not had_subscription:
- # No Stripe subscription drove this change (admin-granted or
- # never-paid).
- await set_subscription_tier(user_id, tier)
- return await get_subscription_status(user_id)
- if not payment_flag_authoritative:
- # An unreadable flag reads False exactly like payment being off, and
- # the DB flip below would strand a still-billing Stripe subscription.
- logger.error(
- f"Refusing to cancel subscription for user {user_id}: "
- f"{Flag.ENABLE_PLATFORM_PAYMENT} could not be evaluated"
- )
- raise HTTPException(
- status_code=502,
- detail=(
- "Unable to cancel your subscription right now. "
- "Please try again or contact support."
- ),
- )
- await set_subscription_tier(user_id, tier)
- return await get_subscription_status(user_id)
-
- if not payment_enabled:
- raise HTTPException(
- status_code=422,
- detail=f"Subscription not available for tier {tier.value}",
- )
-
- # Target has no LD price — not provisionable (matches the GET hiding).
- if target_price_id is None:
- raise HTTPException(
- status_code=422,
- detail=f"Subscription not available for tier {tier.value}",
- )
-
- # Modify in place if there's a sub; else fall through to Checkout below.
- try:
- modified = await modify_stripe_subscription_for_tier(
- user_id, tier, request.billing_cycle
- )
- if modified:
- return await get_subscription_status(user_id)
- except ValueError as e:
- raise HTTPException(status_code=422, detail=str(e))
- except stripe.CardError as e:
- # Auto-charge failed under payment_behavior=error_if_incomplete: the
- # modify was rolled back, so 402 lets the UI prompt for a new card or
- # surface SCA. SCA codes mean the card is fine but the bank wants 3DS —
- # different message so the user doesn't try a new card. Stripe emits
- # ``authentication_required`` for raw PaymentIntent confirms but
- # ``subscription_payment_intent_requires_action`` for Subscription.modify
- # under ``error_if_incomplete``; both must map to the SCA branch.
- if e.code in {
- "authentication_required",
- "subscription_payment_intent_requires_action",
- }:
- logger.warning(
- "SCA required on subscription upgrade for user %s: %s", user_id, e
- )
- raise HTTPException(
- status_code=402,
- detail=(
- "Your bank requires extra authentication for this charge."
- " The plan was not changed; please retry from the billing"
- " portal so you can complete authentication, or contact"
- " support."
- ),
- )
- logger.warning(
- "Card declined on subscription upgrade for user %s: %s", user_id, e
- )
- raise HTTPException(
- status_code=402,
- detail=(
- "Your card was declined. The plan was not changed; please"
- " update your payment method and try again."
- ),
- )
- except stripe.InvalidRequestError as e:
- # Stripe's e.param is documented as nullable, so we match by typed
- # field first and fall back to substring when param is absent.
- msg_lower = (e.user_message or str(e)).lower()
- # "No payment method" presents as InvalidRequestError (not CardError)
- # when error_if_incomplete fires with no default PM. Stripe signals
- # this with code=resource_missing/missing — sometimes with a typed
- # param, sometimes without (the raw "no attached payment source"
- # message has empty param). Map it to 402 either way.
- if e.code in {"resource_missing", "missing"} and (
- e.param
- in {
- "default_payment_method",
- "payment_method",
- "invoice_settings.default_payment_method",
- }
- or "no attached payment source" in msg_lower
- or "default payment method" in msg_lower
- or "no payment method" in msg_lower
- ):
- logger.warning(
- "No payment method on subscription upgrade for user %s: %s",
- user_id,
- e,
- )
- raise HTTPException(
- status_code=402,
- detail=(
- "No payment method on file. The plan was not changed;"
- " please add a payment method and try again."
- ),
- )
- # Stripe rejects schedule modify when phases mix currencies, e.g. the
- # active sub was checked out in GBP but the target tier's Price is
- # USD-only. e.param is "currency" on the schedule API but may be
- # "phases" or absent on older error shapes — substring fallback keeps
- # the 422 firing instead of dropping to the generic 502.
- if e.param == "currency" or "currency" in msg_lower:
- logger.warning(
- "Currency mismatch on tier change for user %s: %s", user_id, e
- )
- raise HTTPException(
- status_code=422,
- detail=(
- "Tier change unavailable for your current billing currency."
- " Please contact support — the target tier needs to be"
- " configured for your currency in Stripe before this"
- " change can go through."
- ),
- )
- logger.exception(
- "Stripe error modifying subscription for user %s: %s", user_id, e
- )
- raise HTTPException(
- status_code=502,
- detail=(
- "Unable to update your subscription right now. "
- "Please try again or contact support."
- ),
- )
- except stripe.StripeError as e:
- logger.exception(
- "Stripe error modifying subscription for user %s: %s", user_id, e
- )
- raise HTTPException(
- status_code=502,
- detail=(
- "Unable to update your subscription right now. "
- "Please try again or contact support."
- ),
- )
-
- # No active Stripe subscription → create Stripe Checkout Session.
- if not request.success_url or not request.cancel_url:
- raise HTTPException(
- status_code=422,
- detail="success_url and cancel_url are required for paid tier upgrades",
- )
- # Open-redirect protection: both URLs must point to the configured frontend
- # origin, otherwise an attacker could use our Stripe integration as a
- # redirector to arbitrary phishing sites.
- #
- # Fail early with a clear 503 if the server is misconfigured (neither
- # frontend_base_url nor platform_base_url set), so operators get an
- # actionable error instead of the misleading "must match the platform
- # frontend origin" 422 that _validate_checkout_redirect_url would otherwise
- # produce when `allowed` is empty.
- if not (settings.config.frontend_base_url or settings.config.platform_base_url):
- logger.error(
- "update_subscription_tier: neither frontend_base_url nor "
- "platform_base_url is configured; cannot validate checkout redirect URLs"
- )
- raise HTTPException(
- status_code=503,
- detail=(
- "Payment redirect URLs cannot be validated: "
- "frontend_base_url or platform_base_url must be set on the server."
- ),
- )
- if not _validate_checkout_redirect_url(
- request.success_url
- ) or not _validate_checkout_redirect_url(request.cancel_url):
- raise HTTPException(
- status_code=422,
- detail="success_url and cancel_url must match the platform frontend origin",
- )
- try:
- url = await create_subscription_checkout(
- user_id=user_id,
- tier=tier,
- success_url=request.success_url,
- cancel_url=request.cancel_url,
- billing_cycle=request.billing_cycle,
- datafast_visitor_id=x_datafast_visitor_id,
- datafast_session_id=x_datafast_session_id,
- )
- except ValueError as e:
- raise HTTPException(status_code=422, detail=str(e))
- except stripe.StripeError as e:
- logger.exception(
- "Stripe error creating checkout session for user %s: %s", user_id, e
- )
- raise HTTPException(
- status_code=502,
- detail=(
- "Unable to start checkout right now. "
- "Please try again or contact support."
- ),
- )
-
- status = await get_subscription_status(user_id)
- status.url = url
- return status
-
-
-def _stripe_event_dedup_key(event_id: str) -> str:
- return f"stripe_webhook_event:{event_id}"
-
-
-async def _claim_stripe_event(event_id: str) -> bool:
- """Mark a Stripe webhook event as claimed via Redis SETNX.
-
- Returns ``True`` when the caller acquired the claim (first time we've seen
- ``event_id``) and should proceed with handler dispatch. Returns ``False``
- when the event was already processed in a prior delivery — Stripe retries
- the same ``event.id`` on non-2xx responses, and we don't want downstream
- handlers (some of which only carry per-resource idempotency) to fire twice.
-
- Pair with ``_release_stripe_event`` in a try/except around handler dispatch:
- on handler failure we DELete the key so Stripe's retry isn't no-op'd, but
- a retry that arrives *during* in-flight processing still hits the live
- claim and is deduped.
-
- TTL of 24h comfortably exceeds Stripe's retry window. On Redis failure we
- fall open and let processing continue — better to risk a rare duplicate
- than to drop a real event.
- """
- if not event_id:
- # Malformed event without an id — fall open so the rest of the
- # handler can decide what to do (it'll log and 200 anyway).
- return True
- try:
- redis_client = await get_redis_async()
- claimed = await redis_client.set(
- _stripe_event_dedup_key(event_id), "1", nx=True, ex=86400
- )
- return bool(claimed)
- except Exception:
- logger.warning(
- "stripe_webhook: dedup claim failed for event %s; processing anyway",
- event_id,
- exc_info=True,
- )
- return True
-
-
-async def _notify_checkout_completed(session: dict) -> None:
- """Hand the completed checkout to the lifecycle emails.
-
- Failures here must not fail the webhook: the customer has paid, and Stripe
- retrying the whole event would re-run `fulfill_checkout`, which grants
- credits. But swallowing the failure lost the welcome permanently — Stripe
- does not retry a 200, and `customer.subscription.created` deliberately does
- not send it either.
-
- So the work is queued rather than done here. The consumer re-reads the
- session and subscription from Stripe and sends the welcome, with the same
- retry-with-backoff and dead-letter queue every other notification gets.
- Publishing is one small call that either succeeds or is logged; the Stripe
- API round-trip and the email now sit behind a retry instead of a warning.
- """
- if session.get("mode") != "subscription":
- return
- if not session.get("subscription"):
- return
- session_id = session.get("id")
- if not session_id:
- return
- result = await queue_pass_work(
- PassWorkKind.WELCOME.value,
- str(session_id),
- PassWorkEvent(
- kind=PassWorkKind.WELCOME,
- user_id="",
- scheduled_for=datetime.now(tz=timezone.utc),
- context={"session_id": str(session_id)},
- ).model_dump_json(),
- )
- if not result.success:
- if (session.get("metadata") or {}).get("trial_enrollment_id"):
- raise RuntimeError("Could not queue the trial welcome notice")
- logger.warning(
- "stripe_webhook: could not queue the welcome email for session %s: %s",
- session_id,
- result.message,
- )
-
-
-async def _release_stripe_event(event_id: str) -> None:
- """Release a previously-claimed dedup key so Stripe's retry can rerun."""
- if not event_id:
- return
- try:
- redis_client = await get_redis_async()
- await redis_client.delete(_stripe_event_dedup_key(event_id))
- except Exception:
- logger.warning(
- "stripe_webhook: dedup release failed for event %s",
- event_id,
- exc_info=True,
- )
-
-
-@v1_router.post(
- path="/credits/stripe_webhook", summary="Handle Stripe webhooks", tags=["credits"]
-)
-async def stripe_webhook(request: Request):
- webhook_secret = settings.secrets.stripe_webhook_secret
- if not webhook_secret:
- # Guard: an empty secret allows HMAC forgery (attacker can compute a valid
- # signature over the same empty key). Reject all webhook calls when unconfigured.
- logger.error(
- "stripe_webhook: STRIPE_WEBHOOK_SECRET is not configured — "
- "rejecting request to prevent signature bypass"
- )
- raise HTTPException(status_code=503, detail="Webhook not configured")
-
- # Get the raw request body
- payload = await request.body()
- # Get the signature header
- sig_header = request.headers.get("stripe-signature")
-
- try:
- event = stripe.Webhook.construct_event(payload, sig_header, webhook_secret)
- except ValueError:
- # Invalid payload
- raise HTTPException(status_code=400, detail="Invalid payload")
- except stripe.SignatureVerificationError:
- # Invalid signature
- raise HTTPException(status_code=400, detail="Invalid signature")
-
- # Defensive payload extraction. A malformed payload (missing/non-dict
- # `data.object`, missing `id`) would otherwise raise KeyError/TypeError
- # AFTER signature verification — which Stripe interprets as a delivery
- # failure and retries forever, while spamming Sentry with no useful info.
- # Acknowledge with 200 and a warning so Stripe stops retrying.
- event_id = event.get("id", "")
- event_type = event.get("type", "")
-
- if event_type in TRIAL_BILLING_EVENTS:
- # This idempotent path only reconciles current Stripe state. Do not let
- # a claim left by a crashed delivery suppress card removal/restoration.
- await sync_trials_for_billing_event(event_type, event.get("data"))
- return Response(status_code=200)
-
- # Event-level dedup: short-circuit identical re-deliveries before any
- # handler runs. Stripe retries the same event.id on non-2xx responses, and
- # not every downstream handler is independently idempotent.
- if not await _claim_stripe_event(event_id):
- logger.info(
- "stripe_webhook: event %s (%s) already processed; skipping",
- event_id,
- event_type,
- )
- return Response(status_code=200)
-
- event_data = event.get("data") or {}
- data_object = event_data.get("object") if isinstance(event_data, dict) else None
- if not isinstance(data_object, dict):
- logger.warning(
- "stripe_webhook: %s missing or non-dict data.object; ignoring",
- event_type,
- )
- return Response(status_code=200)
-
- # Wrap handler dispatch so a downstream failure releases the dedup claim;
- # otherwise Stripe's retry would hit the live key and silently drop the
- # event. Concurrent retries that arrive *during* in-flight processing
- # still hit the live claim and are deduped.
- try:
- if event_type in (
- "checkout.session.completed",
- "checkout.session.async_payment_succeeded",
- ):
- session_id = data_object.get("id")
- if not session_id:
- logger.warning(
- "stripe_webhook: %s missing data.object.id; ignoring", event_type
- )
- return Response(status_code=200)
- await UserCredit().fulfill_checkout(session_id=session_id)
- await sync_tier_from_checkout_session(data_object)
- # Only `checkout.session.completed` drives the welcome email.
- # `customer.subscription.created` fires at signup too; listening to
- # both would double-send.
- if event_type == "checkout.session.completed":
- await _notify_checkout_completed(data_object)
-
- if event_type in (
- "customer.subscription.created",
- "customer.subscription.updated",
- "customer.subscription.deleted",
- ):
- await sync_subscription_from_stripe(data_object)
- if event_type == "customer.subscription.updated":
- await lifecycle.on_subscription_updated(
- data_object, event_data.get("previous_attributes") or {}
- )
- elif event_type == "customer.subscription.deleted":
- await lifecycle.on_subscription_deleted(data_object)
-
- # `subscription_schedule.updated` is deliberately omitted: our own
- # `SubscriptionSchedule.create` + `.modify` calls in
- # `_schedule_downgrade_at_period_end` would fire that event right back
- # at us and loop redundant traffic through this handler. We only care
- # about state transitions (released / completed); phase advance to
- # the new price is already covered by `customer.subscription.updated`.
- if event_type in (
- "subscription_schedule.released",
- "subscription_schedule.completed",
- ):
- await sync_subscription_schedule_from_stripe(data_object)
-
- if event_type == "invoice.payment_succeeded":
- await handle_subscription_payment_success(data_object)
- await on_trial_invoice(data_object, paid=True)
-
- if event_type == "customer.subscription.trial_will_end":
- await sync_subscription_from_stripe(data_object)
- await notify_trial(data_object, "ending")
-
- if event_type == "invoice.payment_failed":
- await handle_subscription_payment_failure(data_object)
- if not await on_trial_invoice(data_object, paid=False):
- await lifecycle.on_payment_failed(data_object)
-
- # New Stripe API (≥2025-04-01) split the per-payment events off the
- # Invoice resource. data.object is an InvoicePayment, not an Invoice,
- # so we hydrate the underlying Invoice before delegating to the
- # existing handlers. A transient ``stripe.StripeError`` here propagates
- # to the outer handler so the dedup claim is released and Stripe sees
- # a 5xx + retries — swallowing it with a 200 would silently drop the
- # event and leave the dedup key blocking the next delivery.
- if event_type in ("invoice_payment.paid", "invoice_payment.payment_failed"):
- invoice_id = data_object.get("invoice")
- if invoice_id:
- invoice = await stripe_call(stripe.Invoice.retrieve_async, invoice_id)
- invoice_payload = cast(dict, invoice)
- if event_type == "invoice_payment.paid":
- await handle_subscription_payment_success(invoice_payload)
- await on_trial_invoice(invoice_payload, paid=True)
- else:
- await handle_subscription_payment_failure(invoice_payload)
- if not await on_trial_invoice(invoice_payload, paid=False):
- await lifecycle.on_payment_failed(invoice_payload)
-
- # `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects
- # (Dispute/Refund). The Stripe webhook payload's `data.object` is a
- # StripeObject (a dict subclass) carrying that runtime shape, so we
- # cast to satisfy the type checker without changing runtime behaviour.
- if event_type == "charge.dispute.created":
- await UserCredit().handle_dispute(cast(stripe.Dispute, data_object))
-
- if event_type == "refund.created" or event_type == "charge.dispute.closed":
- await UserCredit().deduct_credits(
- cast("stripe.Refund | stripe.Dispute", data_object)
- )
- except Exception:
- # Release the dedup claim so Stripe's retry isn't no-op'd. Re-raise
- # so the webhook returns 500 and Stripe retries (the normal contract).
- await _release_stripe_event(event_id)
- raise
-
- return Response(status_code=200)
-
-
-@v1_router.get(
- path="/credits/manage",
- tags=["credits"],
- summary="Manage payment methods",
- dependencies=[Security(requires_user)],
-)
-async def manage_payment_method(
- user_id: Annotated[str, Security(get_user_id)],
- ctx: Annotated[RequestContext, Security(get_request_context)],
-) -> 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)}
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.py
index 8669817036..b72346776c 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
@@ -40,13 +40,18 @@ from backend.data.model import AutoTopUpConfig, TransactionHistory
from backend.data.org_credit import OrgCreditModel
from .billing.credits import routes as credits_routes
+from .billing.subscriptions import routes as subscriptions_routes
from .v1 import v1_router
app = 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.
+# Both halves of /credits now live in their own modules. v1_router stays mounted
+# because this suite's role matrix still reaches routes left behind in it; every
+# further layer that moves a /credits route has to add its router here too, and
+# the durable fix is to give the request-level tests the real app as the two
+# introspection tests already use.
app.include_router(v1_router)
app.include_router(credits_routes.router)
+app.include_router(subscriptions_routes.router)
client = fastapi.testclient.TestClient(app)
ORG_ID = "test-org"
@@ -220,10 +225,13 @@ 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)
+ # manage_payment_method moved to the subscriptions module with #14477 and
+ # resolves that module's own get_credit_model — so the suite spans two
+ # modules and both bindings need stubbing.
+ mocker.patch(
+ "backend.api.features.billing.subscriptions.routes.get_credit_model",
+ return_value=model,
+ )
return CreditStubs(
get_credit_model=mocker.patch(
"backend.api.features.billing.credits.routes.get_credit_model",
diff --git a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
index b616959e17..d1b29b1579 100644
--- a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
@@ -16,10 +16,14 @@ from backend.data.credit import (
)
from backend.data.notifications import NotificationResult, PassWorkEvent, PassWorkKind
-from .v1 import _claim_stripe_event, _release_stripe_event, v1_router
+from .billing.subscriptions.routes import (
+ _claim_stripe_event,
+ _release_stripe_event,
+ router,
+)
app = fastapi.FastAPI()
-app.include_router(v1_router)
+app.include_router(router)
client = fastapi.testclient.TestClient(app)
@@ -41,20 +45,20 @@ def stub_lifecycle_emails(mocker: pytest_mock.MockFixture):
# re-run `fulfill_checkout`. The consumer re-reads the session from
# Stripe and sends it, with retries and a DLQ.
"checkout": mocker.patch(
- "backend.api.features.v1.queue_pass_work",
+ "backend.api.features.billing.subscriptions.routes.queue_pass_work",
new_callable=AsyncMock,
return_value=NotificationResult(success=True),
),
"payment_failed": mocker.patch(
- "backend.api.features.v1.lifecycle.on_payment_failed",
+ "backend.api.features.billing.subscriptions.routes.lifecycle.on_payment_failed",
new_callable=AsyncMock,
),
"updated": mocker.patch(
- "backend.api.features.v1.lifecycle.on_subscription_updated",
+ "backend.api.features.billing.subscriptions.routes.lifecycle.on_subscription_updated",
new_callable=AsyncMock,
),
"deleted": mocker.patch(
- "backend.api.features.v1.lifecycle.on_subscription_deleted",
+ "backend.api.features.billing.subscriptions.routes.lifecycle.on_subscription_deleted",
new_callable=AsyncMock,
),
}
@@ -86,14 +90,15 @@ def test_stripe_webhook_checkout_calls_sync_tier_helper(
return_value=_make_checkout_event("subscription", "sub_123"),
)
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.UserCredit.fulfill_checkout",
+ new_callable=AsyncMock,
)
mock_sync = mocker.patch(
- "backend.api.features.v1.sync_tier_from_checkout_session",
+ "backend.api.features.billing.subscriptions.routes.sync_tier_from_checkout_session",
new_callable=AsyncMock,
)
@@ -124,20 +129,21 @@ def test_stripe_webhook_skips_handlers_on_replayed_event(
return_value=event,
)
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
# Simulate "this event was already processed".
mocker.patch(
- "backend.api.features.v1._claim_stripe_event",
+ "backend.api.features.billing.subscriptions.routes._claim_stripe_event",
new_callable=AsyncMock,
return_value=False,
)
mock_fulfill = mocker.patch(
- "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.UserCredit.fulfill_checkout",
+ new_callable=AsyncMock,
)
mock_sync = mocker.patch(
- "backend.api.features.v1.sync_tier_from_checkout_session",
+ "backend.api.features.billing.subscriptions.routes.sync_tier_from_checkout_session",
new_callable=AsyncMock,
)
@@ -161,14 +167,15 @@ def test_stripe_webhook_checkout_propagates_sync_failure(
return_value=_make_checkout_event("subscription", "sub_err"),
)
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.UserCredit.fulfill_checkout",
+ new_callable=AsyncMock,
)
mocker.patch(
- "backend.api.features.v1.sync_tier_from_checkout_session",
+ "backend.api.features.billing.subscriptions.routes.sync_tier_from_checkout_session",
new_callable=AsyncMock,
side_effect=stripe.StripeError("network error"),
)
@@ -200,23 +207,24 @@ def test_stripe_webhook_releases_dedup_claim_on_handler_failure(
return_value=event,
)
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1._claim_stripe_event",
+ "backend.api.features.billing.subscriptions.routes._claim_stripe_event",
new_callable=AsyncMock,
return_value=True,
)
mock_release = mocker.patch(
- "backend.api.features.v1._release_stripe_event",
+ "backend.api.features.billing.subscriptions.routes._release_stripe_event",
new_callable=AsyncMock,
)
mocker.patch(
- "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.UserCredit.fulfill_checkout",
+ new_callable=AsyncMock,
)
mocker.patch(
- "backend.api.features.v1.sync_tier_from_checkout_session",
+ "backend.api.features.billing.subscriptions.routes.sync_tier_from_checkout_session",
new_callable=AsyncMock,
side_effect=stripe.StripeError("downstream blew up"),
)
@@ -252,20 +260,20 @@ def test_stripe_webhook_releases_dedup_on_invoice_retrieve_failure(
return_value=event,
)
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
mocker.patch(
- "backend.api.features.v1._claim_stripe_event",
+ "backend.api.features.billing.subscriptions.routes._claim_stripe_event",
new_callable=AsyncMock,
return_value=True,
)
mock_release = mocker.patch(
- "backend.api.features.v1._release_stripe_event",
+ "backend.api.features.billing.subscriptions.routes._release_stripe_event",
new_callable=AsyncMock,
)
mocker.patch(
- "backend.api.features.v1.stripe.Invoice.retrieve_async",
+ "backend.api.features.billing.subscriptions.routes.stripe.Invoice.retrieve_async",
side_effect=stripe.StripeError("stripe down"),
)
@@ -296,7 +304,7 @@ async def test_claim_stripe_event_first_delivery_returns_true(
redis_mock = MagicMock()
redis_mock.set = AsyncMock(return_value=True)
mocker.patch(
- "backend.api.features.v1.get_redis_async",
+ "backend.api.features.billing.subscriptions.routes.get_redis_async",
new_callable=AsyncMock,
return_value=redis_mock,
)
@@ -316,7 +324,7 @@ async def test_claim_stripe_event_replay_returns_false(
redis_mock = MagicMock()
redis_mock.set = AsyncMock(return_value=None)
mocker.patch(
- "backend.api.features.v1.get_redis_async",
+ "backend.api.features.billing.subscriptions.routes.get_redis_async",
new_callable=AsyncMock,
return_value=redis_mock,
)
@@ -338,7 +346,7 @@ async def test_claim_stripe_event_redis_error_falls_open(
"""Redis unavailable → fall open and let processing continue. Better to
risk a rare duplicate than to drop a real event during a Redis outage."""
mocker.patch(
- "backend.api.features.v1.get_redis_async",
+ "backend.api.features.billing.subscriptions.routes.get_redis_async",
new_callable=AsyncMock,
side_effect=RuntimeError("redis cluster down"),
)
@@ -355,7 +363,7 @@ async def test_release_stripe_event_deletes_key(
redis_mock = MagicMock()
redis_mock.delete = AsyncMock()
mocker.patch(
- "backend.api.features.v1.get_redis_async",
+ "backend.api.features.billing.subscriptions.routes.get_redis_async",
new_callable=AsyncMock,
return_value=redis_mock,
)
@@ -378,7 +386,7 @@ async def test_release_stripe_event_swallows_redis_error(
"""Redis errors during release must not propagate — we're already on
the failure path and re-raising would mask the original error."""
mocker.patch(
- "backend.api.features.v1.get_redis_async",
+ "backend.api.features.billing.subscriptions.routes.get_redis_async",
new_callable=AsyncMock,
side_effect=RuntimeError("redis cluster down"),
)
@@ -736,7 +744,7 @@ async def test_reconcile_stripe_tier_active_sub_unchanged_returns_false(
def _post_event(mocker: pytest_mock.MockFixture, event: dict) -> None:
mocker.patch("stripe.Webhook.construct_event", return_value=event)
mocker.patch(
- "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ "backend.api.features.billing.subscriptions.routes.settings.secrets.stripe_webhook_secret",
new="whsec_test",
)
response = client.post(
@@ -752,10 +760,11 @@ def test_welcome_email_hangs_off_checkout_not_subscription_created(
) -> None:
"""Both events fire at signup; listening to both would double-send."""
mocker.patch(
- "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.UserCredit.fulfill_checkout",
+ new_callable=AsyncMock,
)
mocker.patch(
- "backend.api.features.v1.sync_tier_from_checkout_session",
+ "backend.api.features.billing.subscriptions.routes.sync_tier_from_checkout_session",
new_callable=AsyncMock,
)
_post_event(mocker, _make_checkout_event("subscription", "sub_123"))
@@ -769,7 +778,8 @@ def test_welcome_email_hangs_off_checkout_not_subscription_created(
stub_lifecycle_emails["checkout"].reset_mock()
mocker.patch(
- "backend.api.features.v1.sync_subscription_from_stripe", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
)
_post_event(
mocker,
@@ -787,7 +797,8 @@ def test_subscription_updated_passes_previous_attributes_through(
"""The cancel/resume emails fire on the flip, which is only visible in
previous_attributes."""
mocker.patch(
- "backend.api.features.v1.sync_subscription_from_stripe", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
)
_post_event(
mocker,
@@ -808,7 +819,8 @@ def test_subscription_deleted_triggers_the_plan_ended_email(
mocker: pytest_mock.MockFixture, stub_lifecycle_emails
) -> None:
mocker.patch(
- "backend.api.features.v1.sync_subscription_from_stripe", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
)
_post_event(
mocker,
@@ -824,7 +836,7 @@ def test_payment_failure_triggers_the_payment_email(
mocker: pytest_mock.MockFixture, stub_lifecycle_emails
) -> None:
mocker.patch(
- "backend.api.features.v1.handle_subscription_payment_failure",
+ "backend.api.features.billing.subscriptions.routes.handle_subscription_payment_failure",
new_callable=AsyncMock,
)
_post_event(
@@ -841,11 +853,12 @@ def test_trial_ending_event_reconciles_and_queues_trial_reminder(
mocker: pytest_mock.MockFixture, stub_lifecycle_emails
) -> None:
sync = mocker.patch(
- "backend.api.features.v1.sync_subscription_from_stripe",
+ "backend.api.features.billing.subscriptions.routes.sync_subscription_from_stripe",
new_callable=AsyncMock,
)
notify = mocker.patch(
- "backend.api.features.v1.notify_trial", new_callable=AsyncMock
+ "backend.api.features.billing.subscriptions.routes.notify_trial",
+ new_callable=AsyncMock,
)
subscription = {
"id": "sub_1",
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index 2c2211944b..353cd7c273 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -239,17 +239,19 @@ def test_execute_graph_block(
return_value=mock_user,
)
- # Default to free block: cost = 0, no charge call.
+ # Default to free block: cost = 0, no charge call. The credit model is
+ # patched where the charge would actually go through — the sibling
+ # charging test below patches the same target — so "not awaited" is a
+ # claim about the code path rather than about an unrelated mock.
cost_mock = mocker.patch(
"backend.api.features.v1.execution_utils.block_usage_cost",
return_value=(0, {}),
)
mock_credit_model = mocker.AsyncMock()
mocker.patch(
- "backend.api.features.v1.get_credit_model",
+ "backend.executor.utils.get_user_credit_model",
return_value=mock_credit_model,
)
-
request_data = {
"input_name": "test_input",
"input_value": "test_value",
diff --git a/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py
index 0c489b33d6..4717206fd3 100644
--- a/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_trial_billing_webhook_test.py
@@ -10,19 +10,25 @@ import fastapi
import fastapi.testclient
import pytest
-from backend.api.features import v1
+from backend.api.features.billing.subscriptions import routes as subscriptions_routes
app = fastapi.FastAPI()
-app.include_router(v1.v1_router)
+app.include_router(subscriptions_routes.router)
client = fastapi.testclient.TestClient(app, raise_server_exceptions=False)
TEST_SECRET = "whsec_trial_billing_test_only"
@pytest.fixture
def billing_refresh(mocker):
- mocker.patch.object(v1.settings.secrets, "stripe_webhook_secret", TEST_SECRET)
- mocker.patch.object(v1, "_claim_stripe_event", AsyncMock(return_value=True))
- return mocker.patch.object(v1, "sync_trials_for_billing_event", AsyncMock())
+ mocker.patch.object(
+ subscriptions_routes.settings.secrets, "stripe_webhook_secret", TEST_SECRET
+ )
+ mocker.patch.object(
+ subscriptions_routes, "_claim_stripe_event", AsyncMock(return_value=True)
+ )
+ return mocker.patch.object(
+ subscriptions_routes, "sync_trials_for_billing_event", AsyncMock()
+ )
def signed_request(event_type, data=None, secret=TEST_SECRET):
@@ -82,7 +88,9 @@ def test_invalid_signature_cannot_refresh_trial(billing_refresh):
def test_unconfigured_webhook_cannot_refresh_trial(billing_refresh, mocker):
- mocker.patch.object(v1.settings.secrets, "stripe_webhook_secret", "")
+ mocker.patch.object(
+ subscriptions_routes.settings.secrets, "stripe_webhook_secret", ""
+ )
response = signed_request("customer.updated")
assert response.status_code == 503
billing_refresh.assert_not_awaited()
@@ -95,7 +103,7 @@ def test_unrelated_event_does_not_refresh_trial(billing_refresh):
def test_repeated_billing_event_always_refreshes_current_state(billing_refresh, mocker):
claim = mocker.patch.object(
- v1, "_claim_stripe_event", AsyncMock(return_value=False)
+ subscriptions_routes, "_claim_stripe_event", AsyncMock(return_value=False)
)
assert signed_request("customer.updated").status_code == 200
assert signed_request("customer.updated").status_code == 200
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 30fc2cac37..398c49dd36 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -31,6 +31,7 @@ import backend.api.features.admin.test_data_routes
import backend.api.features.api_keys.routes as api_keys_routes
import backend.api.features.auth_email.routes as auth_email_routes
import backend.api.features.billing.credits.routes as credits_routes
+import backend.api.features.billing.subscriptions.routes as subscriptions_routes
import backend.api.features.briefings.routes
import backend.api.features.builder
import backend.api.features.builder.routes
@@ -425,6 +426,11 @@ app.include_router(
tags=["v1", "credits"],
prefix="/api",
)
+app.include_router(
+ subscriptions_routes.router,
+ tags=["v1", "credits"],
+ prefix="/api",
+)
app.include_router(
auth_email_routes.auth_email_router,
prefix="/api/auth/email",