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.

feat(platform): make trial capacity and country eligibility configurable (#14799)

Nicholas Tindleda73bf71dde6
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py
index bdb05d97f9..1f99dbeb34 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service.py
@@ -10,6 +10,7 @@ exists to vouch for the request, without introducing any new shared secret.
"""
import logging
+from typing import Any
import fastapi
import jwt
@@ -94,3 +95,24 @@ def requires_frontend_service(scope: str):
)
return _dependency
+
+
+async def frontend_service_claims(token: str, scope: str) -> dict[str, Any] | None:
+ """The claims of *token* if it is a valid frontend service token granting
+ *scope*, else None.
+
+ For facts the frontend vouches for alongside a user's own request -- where
+ the user's bearer token already occupies ``Authorization`` and a failed
+ check should mean "no such fact", not a 401.
+ """
+ if not get_settings().JWT_JWKS_URL:
+ return None
+ try:
+ payload = await parse_jwt_token_async(token, audience=SERVICE_TOKEN_AUDIENCE)
+ except ValueError:
+ return None
+ if payload.get("sub") != FRONTEND_SERVICE_SUBJECT:
+ return None
+ if scope not in str(payload.get("scope", "")).split():
+ return None
+ return payload
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py
index 572ce18a4b..897bbd6fca 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/service_test.py
@@ -23,6 +23,7 @@ from autogpt_libs.auth.config import Settings
from autogpt_libs.auth.service import (
FRONTEND_SERVICE_SUBJECT,
SERVICE_TOKEN_AUDIENCE,
+ frontend_service_claims,
requires_frontend_service,
)
@@ -165,3 +166,49 @@ def test_garbage_token_is_401(jwks_config):
# test here: a valid Settings() cannot exist without JWT_JWKS_URL (its
# validate() raises), so the guard is unreachable. config_test.py covers that
# enforcement.
+
+
+CLAIM_PAYLOAD = {
+ "sub": FRONTEND_SERVICE_SUBJECT,
+ "aud": SERVICE_TOKEN_AUDIENCE,
+ "scope": "client-country",
+ "country": "US",
+}
+
+
+async def test_frontend_service_claims_returns_a_vouched_claim(jwks_config):
+ token = create_es256_token(CLAIM_PAYLOAD, jwks_config)
+ claims = await frontend_service_claims(token, "client-country")
+ assert claims is not None and claims["country"] == "US"
+
+
+ "payload",
+ [
+ {**CLAIM_PAYLOAD, "scope": "auth-email:send"},
+ {**CLAIM_PAYLOAD, "sub": "service:imposter"},
+ {**CLAIM_PAYLOAD, "aud": "authenticated"},
+ {**CLAIM_PAYLOAD, "exp": datetime.now(timezone.utc) - timedelta(minutes=1)},
+ ],
+ ids=["other-scope", "wrong-subject", "user-audience", "expired"],
+)
+async def test_frontend_service_claims_refuses_anything_else(jwks_config, payload):
+ token = create_es256_token(payload, jwks_config)
+ assert await frontend_service_claims(token, "client-country") is None
+
+
+async def test_frontend_service_claims_refuses_a_foreign_signature(jwks_config):
+ """A token the caller signed itself -- the spoofing case -- is no claim."""
+ forged_key, _ = make_es256_keypair()
+ token = create_es256_token(CLAIM_PAYLOAD, forged_key)
+ assert await frontend_service_claims(token, "client-country") is None
+
+
+async def test_frontend_service_claims_refuses_symmetric_and_garbage(jwks_config):
+ hs = jwt.encode(CLAIM_PAYLOAD, MOCK_JWT_SECRET, algorithm="HS256")
+ assert await frontend_service_claims(hs, "client-country") is None
+ assert await frontend_service_claims("US", "client-country") is None
diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py
index 63365241bd..d3993395d2 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py
@@ -3,6 +3,7 @@ from typing import Annotated, Literal
import stripe
from autogpt_libs.auth import get_user_id
+from autogpt_libs.auth.service import frontend_service_claims
from fastapi import APIRouter, Depends, Header, HTTPException, Security
from pydantic import BaseModel, Field
@@ -15,6 +16,7 @@ from backend.data.subscription_trial import (
get_subscription_trial,
has_received_onboarding_credit,
)
+from backend.data.subscription_trial_capacity import trial_seat_available
from backend.data.subscription_trial_checkout import (
TrialUnavailable,
confirm_trial_checkout,
@@ -71,15 +73,48 @@ class TrialCheckoutResponse(BaseModel):
url: str
+CLIENT_COUNTRY_SCOPE = "client-country"
+
+
+async def attested_country(
+ token: Annotated[
+ str | None, Header(alias="X-Client-Country-Token", include_in_schema=False)
+ ] = None,
+) -> str | None:
+ """The visitor's country, as the frontend proxy vouches for it, or None.
+
+ The backend is reachable directly -- the browser already calls it with
+ its own bearer token -- so a plain country header would be whatever the
+ caller typed. The proxy instead sends what Vercel's edge geolocated inside
+ a short-lived frontend service token, signed with the JWKS key only the
+ frontend holds. Anything else -- no token, a forged or expired one, a
+ user token -- is no country at all, which the offer's country rule treats
+ as unknown and withholds. Hidden from the schema: it is proxy-to-backend
+ plumbing, not API surface.
+ """
+ if not token:
+ return None
+ claims = await frontend_service_claims(token, CLIENT_COUNTRY_SCOPE)
+ country = claims.get("country") if claims else None
+ return country if isinstance(country, str) else None
+
+
+ClientCountry = Annotated[str | None, Depends(attested_country)]
+
+
@router.get("")
-async def get_trial_status(user_id: CurrentUser) -> TrialStatusResponse:
+async def get_trial_status(
+ user_id: CurrentUser, country: ClientCountry = None
+) -> TrialStatusResponse:
trial = await get_subscription_trial(user_id)
if trial:
return TrialStatusResponse(
eligible=(
trial.status == "checkout_pending"
and trial.consumed_at is None
- and await get_trial_offer(user_id) is not None
+ and (offer := await get_trial_offer(user_id, country=country))
+ is not None
+ and await trial_seat_available(offer, trial_id=trial.id)
),
offer=TrialOfferResponse.from_offer(trial.offer),
status=trial.status,
@@ -95,8 +130,8 @@ async def get_trial_status(user_id: CurrentUser) -> TrialStatusResponse:
100, 100 * trial.cost_microdollars / trial.offer.total_cost_limit
),
)
- offer = await get_trial_offer(user_id)
- if offer is None:
+ offer = await get_trial_offer(user_id, country=country)
+ if offer is None or not await trial_seat_available(offer):
return TrialStatusResponse()
user = await get_user_by_id(user_id)
has_history = False
@@ -138,6 +173,7 @@ async def get_trial_status(user_id: CurrentUser) -> TrialStatusResponse:
async def start_trial_checkout(
body: TrialCheckoutRequest,
user_id: CurrentUser,
+ country: ClientCountry = None,
x_datafast_visitor_id: Annotated[str | None, Header()] = None,
x_datafast_session_id: Annotated[str | None, Header()] = None,
) -> TrialCheckoutResponse:
@@ -156,6 +192,7 @@ async def start_trial_checkout(
success_url=f"{destination}?trial=success",
cancel_url=f"{destination}?trial=cancelled",
metadata=_datafast_metadata(x_datafast_visitor_id, x_datafast_session_id),
+ country=country,
)
except TrialUnavailable as exc:
raise HTTPException(409, str(exc)) from exc
diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py
index 42a3bc4ab8..0a9f2be39e 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py
@@ -1,9 +1,15 @@
from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock, MagicMock, patch
+import jwt
import pytest
+from autogpt_libs.auth import config as auth_config
+from autogpt_libs.auth import jwt_utils
+from autogpt_libs.auth.service import FRONTEND_SERVICE_SUBJECT, SERVICE_TOKEN_AUDIENCE
+from cryptography.hazmat.primitives.asymmetric import ec
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
+from jwt.algorithms import ECAlgorithm
from backend.api.features import subscription_trial_routes as routes
from backend.data.subscription_trial import TrialState
@@ -241,3 +247,204 @@ async def test_cancellation_cannot_cancel_another_customer_or_paid_plan(
await routes.cancel_trial(trial.user_id)
assert error.value.status_code == 409
cancel.assert_not_awaited()
+
+
+async def test_full_trial_hides_a_pending_enrollments_offer(trial):
+ """No seat, no card screen: the cap is enforced before anyone pays."""
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=trial.offer)),
+ patch.object(
+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)
+ ),
+ patch.object(
+ routes, "trial_seat_available", AsyncMock(return_value=False)
+ ) as seat,
+ ):
+ status = await routes.get_trial_status(trial.user_id)
+ assert not status.eligible
+ assert seat.await_args.kwargs["trial_id"] == trial.id
+
+
+async def test_pending_enrollment_keeps_its_offer_while_it_holds_a_seat(trial):
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=trial.offer)),
+ patch.object(
+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)
+ ),
+ patch.object(routes, "trial_seat_available", AsyncMock(return_value=True)),
+ ):
+ status = await routes.get_trial_status(trial.user_id)
+ assert status.eligible
+
+
+async def test_full_trial_offers_nothing_to_a_new_visitor(trial):
+ """A first-time visitor sees no offer at all rather than a doomed one."""
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=None)),
+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=trial.offer)),
+ patch.object(routes, "trial_seat_available", AsyncMock(return_value=False)),
+ patch.object(routes, "get_user_by_id", AsyncMock()) as user,
+ ):
+ status = await routes.get_trial_status("user-1")
+ assert not status.eligible
+ assert status.offer is None
+ # answered from the cap alone -- no user lookup, no Stripe round-trip
+ user.assert_not_awaited()
+
+
+def _app(trial):
+ app = FastAPI()
+ app.include_router(routes.router)
+ app.dependency_overrides[routes.get_user_id] = lambda: trial.user_id
+ app.dependency_overrides[routes.enforce_subscription_status_rate_limit] = (
+ lambda: None
+ )
+ return app
+
+
+def _es256_key():
+ return ec.generate_private_key(ec.SECP256R1())
+
+
+def frontend_key(monkeypatch):
+ """The frontend's JWKS signing key, as the backend would fetch it."""
+ key = _es256_key()
+ jwk = ECAlgorithm.to_jwk(key.public_key(), as_dict=True)
+ jwk.update({"kid": "frontend-1", "alg": "ES256", "use": "sig"})
+ monkeypatch.setenv("JWT_JWKS_URL", "https://platform.example.com/api/auth/jwks")
+ monkeypatch.setattr(auth_config, "_settings", auth_config.Settings())
+ monkeypatch.setattr(jwt_utils, "_jwks_client", None)
+ monkeypatch.setattr(jwt_utils, "_jwks_client_url", None)
+ monkeypatch.setattr(jwt.PyJWKClient, "fetch_data", lambda self: {"keys": [jwk]})
+ return key
+
+
+def _country_token(key, country, **overrides) -> str:
+ now = int(datetime.now(UTC).timestamp())
+ claims = {
+ "sub": FRONTEND_SERVICE_SUBJECT,
+ "aud": SERVICE_TOKEN_AUDIENCE,
+ "scope": routes.CLIENT_COUNTRY_SCOPE,
+ "country": country,
+ "iat": now,
+ "exp": now + 60,
+ **overrides,
+ }
+ return jwt.encode(claims, key, algorithm="ES256", headers={"kid": "frontend-1"})
+
+
+async def _status_country(trial, headers) -> str | None:
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=None)),
+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=None)) as offer,
+ ):
+ async with AsyncClient(
+ transport=ASGITransport(app=_app(trial)), base_url="https://example.com"
+ ) as client:
+ response = await client.get("/credits/trial", headers=headers)
+ assert response.status_code == 200
+ assert response.json()["eligible"] is False
+ assert response.json()["offer"] is None
+ return offer.await_args.kwargs["country"]
+
+
+async def test_status_asks_the_flag_with_the_country_the_proxy_signed(
+ trial, frontend_key
+):
+ token = _country_token(frontend_key, "IN")
+ assert await _status_country(trial, {"X-Client-Country-Token": token}) == "IN"
+
+
+async def test_a_country_claimed_directly_to_the_backend_is_ignored(
+ trial, frontend_key
+):
+ """A caller holding its own bearer token can reach the backend without the
+ proxy; whatever country it types in a plain header is no country at all."""
+ headers = {"X-Client-Country": "US", "X-Client-Country-Token": "US"}
+ assert await _status_country(trial, headers) is None
+
+
+ "forge",
+ [
+ # signed with a key the caller made up
+ lambda key: _country_token(_es256_key(), "US"),
+ # a real frontend token, but for another purpose
+ lambda key: _country_token(key, "US", scope="auth-email:send"),
+ # a user's own token presented as the proxy's
+ lambda key: _country_token(key, "US", sub="user-1", aud="authenticated"),
+ lambda key: _country_token(key, "US", exp=1),
+ lambda key: jwt.encode(
+ {
+ "sub": FRONTEND_SERVICE_SUBJECT,
+ "aud": SERVICE_TOKEN_AUDIENCE,
+ "scope": routes.CLIENT_COUNTRY_SCOPE,
+ "country": "US",
+ },
+ "a-shared-secret-anyone-could-guess-0123456789",
+ algorithm="HS256",
+ ),
+ lambda key: _country_token(key, ["US"]),
+ ],
+ ids=["foreign-key", "other-scope", "user-token", "expired", "hs256", "non-string"],
+)
+async def test_a_country_token_the_frontend_did_not_issue_is_ignored(
+ trial, frontend_key, forge
+):
+ headers = {"X-Client-Country-Token": forge(frontend_key)}
+ assert await _status_country(trial, headers) is None
+
+
+async def test_pending_enrollment_is_hidden_once_the_flag_excludes_it(trial):
+ """Reserving while eligible does not keep the offer visible after exclusion."""
+ with (
+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(routes, "get_trial_offer", AsyncMock(return_value=None)),
+ patch.object(
+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)
+ ),
+ ):
+ status = await routes.get_trial_status(trial.user_id, "IN")
+ assert not status.eligible
+
+
+async def test_checkout_carries_only_the_signed_country(trial, frontend_key):
+ with patch.object(
+ routes,
+ "create_trial_checkout",
+ AsyncMock(return_value="https://checkout.stripe.com/test"),
+ ) as checkout:
+ async with AsyncClient(
+ transport=ASGITransport(app=_app(trial)), base_url="https://example.com"
+ ) as client:
+ for headers in (
+ {"X-Client-Country-Token": _country_token(frontend_key, "DE")},
+ {"X-Client-Country": "US"},
+ {},
+ ):
+ response = await client.post(
+ "/credits/trial",
+ json={"offer_token": trial.offer.token},
+ headers=headers,
+ )
+ assert response.status_code == 200
+ countries = [call.kwargs["country"] for call in checkout.await_args_list]
+ assert countries == ["DE", None, None]
+
+
+def test_country_header_is_not_advertised_as_api_surface():
+ """Browsers must not learn to set it; only the proxy does."""
+ app = FastAPI()
+ app.include_router(routes.router)
+ assert "X-Client-Country" not in str(app.openapi())
diff --git a/autogpt_platform/backend/backend/data/subscription_trial.py b/autogpt_platform/backend/backend/data/subscription_trial.py
index a9aff8d82f..a189eec2f2 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial.py
@@ -2,11 +2,17 @@
from datetime import datetime
-from prisma.errors import UniqueViolationError
from prisma.models import CreditTransaction, SubscriptionTrial
from prisma.types import SubscriptionTrialWhereInput
from pydantic import BaseModel, TypeAdapter
+from backend.data.db import transaction
+from backend.data.subscription_trial_capacity import (
+ TRIAL_FULL,
+ TrialCapacityReached,
+ lock_trial_capacity,
+ trial_seat_available,
+)
from backend.data.subscription_trial_config import AcceptedTrialOffer, trial_is_active
from backend.data.subscription_trial_rejection import TrialRejectionReason
from backend.util.json import SafeJson
@@ -103,21 +109,39 @@ async def reserve_subscription_trial(
cancel_url: str,
metadata: dict[str, str],
) -> TrialState:
- try:
- row = await SubscriptionTrial.prisma().create(
+ """Take this user's seat under the offer's cap, or return the one they hold.
+
+ Raises :class:`TrialCapacityReached` when the trial is full.
+
+ The seat is read and taken inside its own short transaction rather than
+ the caller's: the caller keeps a transaction open across its Stripe
+ round-trips, and holding the global capacity lock for that long would
+ queue every other enrolment behind one person's network latency.
+ """
+ async with transaction() as tx:
+ await lock_trial_capacity(tx)
+ existing = await tx.subscriptiontrial.find_unique(where={"userId": user_id})
+ if existing:
+ # An enrolment already on file keeps whatever seat it has; it is
+ # resuming, not competing for a new one.
+ return TrialState.from_db(existing)
+ if not await trial_seat_available(offer, client=tx):
+ raise TrialCapacityReached(TRIAL_FULL)
+ row = await tx.subscriptiontrial.create(
data={
"userId": user_id,
- "offer": SafeJson(offer.model_dump(mode="json")),
+ # The cap is live capacity config, read from the flag each
+ # time, never from here. Leaving it out keeps these rows
+ # readable by code that predates it, so a revert is safe.
+ "offer": SafeJson(
+ offer.model_dump(mode="json", exclude={"max_active_trials"})
+ ),
"stripeCustomerId": customer_id,
"checkoutSuccessUrl": success_url,
"checkoutCancelUrl": cancel_url,
"checkoutMetadata": SafeJson(metadata),
},
)
- except UniqueViolationError:
- row = await SubscriptionTrial.prisma().find_unique_or_raise(
- where={"userId": user_id}
- )
return TrialState.from_db(row)
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_capacity.py b/autogpt_platform/backend/backend/data/subscription_trial_capacity.py
new file mode 100644
index 0000000000..dbc4565589
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_capacity.py
@@ -0,0 +1,158 @@
+"""Global seat cap for concurrent introductory trials.
+
+LaunchDarkly can hold the *number*, but not enforce it: a cap on how many
+people are on trial at once is a count over our own rows, so the count and
+the reservation have to happen together, here.
+
+A seat is occupied by either:
+
+* a **running trial** -- exactly the rows ``trial_is_active`` calls active, so
+ the cap counts the same population the product calls "on trial"; or
+* a **checkout opened recently** -- a card screen someone is standing in
+ front of right now. Without this the cap would be enforced against a count
+ that ignores everyone mid-enrolment, and a burst of simultaneous checkouts
+ would all be admitted.
+
+Seats are taken under an advisory lock and released by time, never by
+cleanup: an abandoned checkout stops counting once ``CHECKOUT_RESERVATION``
+passes. The window is deliberately much shorter than Stripe's 24h session
+expiry -- a day-long hold would let abandoned carts starve a small cap --
+which means someone who leaves checkout open past the window can still
+complete it in that tab, pushing the count one over. Coming back through our
+checkout endpoint instead re-admits them under the lock
+(:func:`renew_trial_seat`), so returners cannot all pass on one free seat. The cap is a throttle on
+enrolment, not an invariant, and it is enforced *before* the card screen so
+that going over costs nothing: no one is ever turned away after paying.
+"""
+
+from datetime import timedelta
+
+from prisma import Prisma
+from pydantic import BaseModel
+
+from backend.data.db import execute_raw_with_schema, query_raw_with_schema, transaction
+from backend.data.subscription_trial_config import TrialOffer
+
+# How long an opened checkout holds a seat. Long enough to type in a card,
+# short enough that abandoned ones free up without a sweeper.
+CHECKOUT_RESERVATION = timedelta(minutes=30)
+
+_CAPACITY_LOCK = "trial-capacity"
+
+TRIAL_FULL = "The trial is full right now. Please check back later."
+
+# One definition of "holding a seat", so the cap and the holder check can
+# never drift apart. $2 is the reservation window.
+_SEAT_HELD = """
+ -- running: mirrors trial_is_active()
+ ("status" = 'trialing' AND "cardVerifiedAt" IS NOT NULL
+ AND "endsAt" > NOW())
+ -- or standing at a checkout opened within the reservation window
+ OR ("status" = 'checkout_pending' AND "consumedAt" IS NULL
+ AND "updatedAt" > NOW() - $2::interval)
+"""
+
+# Row filters, both constants -- $1 is always a bound parameter.
+_EVERY_OTHER_TRIAL = "($1 = '' OR \"id\" <> $1)"
+_ONLY_THIS_TRIAL = '"id" = $1'
+
+
+class TrialCapacityReached(ValueError):
+ """No seat is free under the offer's cap."""
+
+
+class _Seats(BaseModel):
+ seats: int
+
+
+async def trial_seat_available(
+ offer: TrialOffer,
+ *,
+ trial_id: str | None = None,
+ client: Prisma | None = None,
+) -> bool:
+ """May the enrolment ``trial_id`` occupy a seat under *offer*'s cap?
+
+ True when a seat is free, and also when this enrolment already holds
+ one -- otherwise a reservation would be revoked by whoever filled the
+ remaining seats while its owner was still typing in a card.
+
+ Callers about to *take* a seat must hold :func:`lock_trial_capacity` on
+ the same transaction; callers merely deciding whether to show the offer
+ need not, and should tolerate the answer being a moment stale.
+ """
+ if offer.max_active_trials is None:
+ return True
+ if offer.max_active_trials == 0:
+ # A hard pause on enrolment. Seats already held -- running trials and
+ # open checkouts alike -- are kept, but nothing new gets one.
+ return bool(trial_id) and await _holds_seat(trial_id, client=client)
+ held_by_others = await count_trial_seats(exclude_trial_id=trial_id, client=client)
+ if held_by_others < offer.max_active_trials:
+ return True
+ return bool(trial_id) and await _holds_seat(trial_id, client=client)
+
+
+async def renew_trial_seat(offer: TrialOffer, trial_id: str) -> bool:
+ """Re-admit the checkout ``trial_id`` under *offer*'s cap and restart its hold.
+
+ A checkout whose hold has lapsed no longer holds a seat, so returners
+ checked without the lock could each pass on the same free seat. The check
+ and the renewal happen together under the capacity lock, in their own
+ short transaction, before any Stripe call.
+ """
+ if offer.max_active_trials is None:
+ return True
+ async with transaction() as tx:
+ await lock_trial_capacity(tx)
+ if not await trial_seat_available(offer, trial_id=trial_id, client=tx):
+ return False
+ await execute_raw_with_schema(
+ 'UPDATE {schema_prefix}"SubscriptionTrial" SET "updatedAt" = NOW() '
+ 'WHERE "id" = $1 AND "status" = \'checkout_pending\'',
+ trial_id,
+ client=tx,
+ )
+ return True
+
+
+async def lock_trial_capacity(tx: Prisma) -> None:
+ """Serialise seat-taking for the duration of *tx*.
+
+ Held by every caller that counts seats with intent to take one, so two
+ simultaneous enrolments cannot both read the last free seat.
+ """
+ await query_raw_with_schema(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))::text",
+ _CAPACITY_LOCK,
+ client=tx,
+ )
+
+
+async def count_trial_seats(
+ *, exclude_trial_id: str | None = None, client: Prisma | None = None
+) -> int:
+ """Seats currently held, optionally ignoring one enrolment's own seat.
+
+ ``exclude_trial_id`` is what lets a user who already holds a seat resume
+ their own checkout when the trial is otherwise full.
+ """
+ return await _count_seats(_EVERY_OTHER_TRIAL, exclude_trial_id or "", client=client)
+
+
+async def _holds_seat(trial_id: str, *, client: Prisma | None = None) -> bool:
+ return bool(await _count_seats(_ONLY_THIS_TRIAL, trial_id, client=client))
+
+
+async def _count_seats(
+ row_filter: str, target: str, *, client: Prisma | None = None
+) -> int:
+ rows = await query_raw_with_schema(
+ f'SELECT COUNT(*)::int AS seats FROM {{schema_prefix}}"SubscriptionTrial" '
+ f"WHERE {row_filter} AND ({_SEAT_HELD})",
+ target,
+ f"{CHECKOUT_RESERVATION.total_seconds()} seconds",
+ model=_Seats,
+ client=client,
+ )
+ return rows[0].seats if rows else 0
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_capacity_integration_test.py b/autogpt_platform/backend/backend/data/subscription_trial_capacity_integration_test.py
new file mode 100644
index 0000000000..d6720e6acd
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_capacity_integration_test.py
@@ -0,0 +1,222 @@
+"""The seat cap against real Postgres: the SQL, the lock and the race.
+
+Run only against a disposable database with TRIAL_TEST_DATABASE=1.
+"""
+
+import asyncio
+import os
+from datetime import UTC, datetime
+from unittest.mock import patch
+from urllib.parse import urlparse
+from uuid import uuid4
+
+import pytest
+import pytest_asyncio
+from prisma.models import SubscriptionTrial, User
+
+from backend.data import db
+from backend.data import subscription_trial as trials
+from backend.data import subscription_trial_capacity as capacity
+from backend.data.subscription_trial import TrialState, reserve_subscription_trial
+from backend.data.subscription_trial_capacity import (
+ TrialCapacityReached,
+ count_trial_seats,
+ renew_trial_seat,
+ trial_seat_available,
+)
+from backend.data.subscription_trial_config import AcceptedTrialOffer
+
+pytestmark = pytest.mark.skipif(
+ os.environ.get("TRIAL_TEST_DATABASE") != "1",
+ reason="Requires explicitly selected disposable trial database",
+)
+
+
+@pytest_asyncio.fixture
+async def new_user():
+ target = urlparse(db.DATABASE_URL)
+ local = (target.hostname, target.port, target.path) == (
+ "127.0.0.1",
+ 15432,
+ "/trial_test",
+ )
+ ci = os.environ.get("GITHUB_ACTIONS") == "true" and (
+ target.hostname,
+ target.port,
+ target.path,
+ ) == ("localhost", 5432, "/postgres")
+ assert (
+ local or ci
+ ), "Trial integration tests require an approved disposable database"
+ owns_connection = not db.is_connected()
+ await db.connect()
+ created: list[str] = []
+
+ async def make() -> str:
+ user_id = str(uuid4())
+ await User.prisma().create(
+ data={"id": user_id, "email": f"{user_id}@example.com"}
+ )
+ created.append(user_id)
+ return user_id
+
+ yield make
+ await User.prisma().delete_many(where={"id": {"in": created}})
+ if owns_connection:
+ await db.disconnect()
+
+
+def offer(max_active_trials: int | None) -> AcceptedTrialOffer:
+ return AcceptedTrialOffer(
+ version="capacity-integration-v1",
+ new_users_from=datetime(2026, 9, 1, tzinfo=UTC),
+ duration_days=7,
+ tier="PRO",
+ billing_cycle="monthly",
+ daily_cost_limit=250_000,
+ weekly_cost_limit=1_000_000,
+ total_cost_limit=1_000_000,
+ onboarding_credit_amount=300,
+ price_id="price_integration",
+ unit_amount=2000,
+ currency="usd",
+ max_active_trials=max_active_trials,
+ )
+
+
+async def lapse(trial_id: str) -> None:
+ """Age a checkout past the reservation window, so it holds no seat."""
+ await db.execute_raw_with_schema(
+ 'UPDATE {schema_prefix}"SubscriptionTrial" '
+ 'SET "updatedAt" = NOW() - interval \'31 minutes\' WHERE "id" = $1',
+ trial_id,
+ )
+
+
+async def reserve(user_id: str, terms: AcceptedTrialOffer) -> TrialState:
+ return await reserve_subscription_trial(
+ user_id,
+ terms,
+ "cus_integration",
+ "https://example.com/success",
+ "https://example.com/cancel",
+ {},
+ )
+
+
+async def test_two_enrolments_racing_for_the_last_seat_admit_exactly_one(new_user):
+ first, second = await new_user(), await new_user()
+ # Whatever else this database holds, exactly one seat is left.
+ capped = offer(await count_trial_seats() + 1)
+
+ # Each enrolment, having read the count, waits for the other to read it
+ # too before inserting. Without the capacity lock both read the same free
+ # seat and both insert; with it, the second cannot count until the first
+ # has committed, so it waits out the pause and then finds the trial full.
+ counted = 0
+ both_counted = asyncio.Event()
+ real_seat_available = trials.trial_seat_available
+
+ async def count_then_pause(*args, **kwargs):
+ nonlocal counted
+ free = await real_seat_available(*args, **kwargs)
+ counted += 1
+ if counted == 2:
+ both_counted.set()
+ try:
+ await asyncio.wait_for(both_counted.wait(), timeout=2)
+ except TimeoutError:
+ pass
+ return free
+
+ with patch.object(trials, "trial_seat_available", count_then_pause):
+ results = await asyncio.gather(
+ reserve(first, capped), reserve(second, capped), return_exceptions=True
+ )
+
+ winners = [r for r in results if isinstance(r, TrialState)]
+ refused = [r for r in results if isinstance(r, TrialCapacityReached)]
+ assert (len(winners), len(refused)) == (1, 1), results
+ assert await count_trial_seats() == capped.max_active_trials
+ assert (
+ await SubscriptionTrial.prisma().count(
+ where={"userId": {"in": [first, second]}}
+ )
+ == 1
+ )
+
+
+async def test_a_full_trial_keeps_its_holder_and_frees_an_abandoned_checkout(
+ new_user,
+):
+ held = await reserve(await new_user(), offer(None))
+ full = offer(await count_trial_seats())
+
+ assert await trial_seat_available(full) is False
+ # the holder is not crowded out by its own seat
+ assert await trial_seat_available(full, trial_id=held.id) is True
+ assert await count_trial_seats(exclude_trial_id=held.id) == (
+ full.max_active_trials - 1
+ )
+ # pausing enrolment (cap 0) refuses newcomers but keeps the holder
+ assert await trial_seat_available(offer(0)) is False
+ assert await trial_seat_available(offer(0), trial_id=held.id) is True
+
+ # A checkout left open past the reservation window stops holding a seat.
+ await db.execute_raw_with_schema(
+ 'UPDATE {schema_prefix}"SubscriptionTrial" '
+ 'SET "updatedAt" = NOW() - interval \'31 minutes\' WHERE "id" = $1',
+ held.id,
+ )
+ assert await count_trial_seats() == full.max_active_trials - 1
+ assert await trial_seat_available(full) is True
+
+
+async def test_the_stored_offer_leaves_the_cap_out(new_user):
+ """Rows must stay readable by code that predates the cap, so a revert of
+ the cap does not strand every trial enrolled while it was deployed."""
+ held = await reserve(await new_user(), offer(500))
+ row = await SubscriptionTrial.prisma().find_unique_or_raise(where={"id": held.id})
+ assert isinstance(row.offer, dict)
+ assert "max_active_trials" not in row.offer
+ assert held.offer.token == offer(500).token
+
+
+async def test_two_returners_racing_for_the_last_seat_renew_exactly_one(new_user):
+ first = await reserve(await new_user(), offer(None))
+ second = await reserve(await new_user(), offer(None))
+ await lapse(first.id)
+ await lapse(second.id)
+ # Both holds have lapsed, and exactly one seat is free.
+ capped = offer(await count_trial_seats() + 1)
+
+ counted = 0
+ both_counted = asyncio.Event()
+ real_seat_available = capacity.trial_seat_available
+
+ async def count_then_pause(*args, **kwargs):
+ nonlocal counted
+ free = await real_seat_available(*args, **kwargs)
+ counted += 1
+ if counted == 2:
+ both_counted.set()
+ try:
+ await asyncio.wait_for(both_counted.wait(), timeout=2)
+ except TimeoutError:
+ pass
+ return free
+
+ with patch.object(capacity, "trial_seat_available", count_then_pause):
+ renewed = await asyncio.gather(
+ renew_trial_seat(capped, first.id), renew_trial_seat(capped, second.id)
+ )
+
+ assert sorted(renewed) == [False, True]
+ assert await count_trial_seats() == capped.max_active_trials
+ winner = first if renewed[0] else second
+ # the winner's hold restarted, so it keeps its seat for a new window
+ assert await trial_seat_available(capped, trial_id=winner.id) is True
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_capacity_test.py b/autogpt_platform/backend/backend/data/subscription_trial_capacity_test.py
new file mode 100644
index 0000000000..4654814ab9
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_capacity_test.py
@@ -0,0 +1,168 @@
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.data import subscription_trial_capacity as capacity
+from backend.data.subscription_trial_config import TrialOffer
+
+
+def offer(max_active_trials: int | None) -> TrialOffer:
+ return TrialOffer.model_validate(
+ {
+ "version": "capacity-v1",
+ "new_users_from": datetime.now(UTC) - timedelta(days=1),
+ "duration_days": 7,
+ "tier": "PRO",
+ "billing_cycle": "monthly",
+ "daily_cost_limit": 250_000,
+ "weekly_cost_limit": 1_000_000,
+ "total_cost_limit": 1_000_000,
+ "onboarding_credit_amount": 300,
+ "max_active_trials": max_active_trials,
+ }
+ )
+
+
+ "cap,taken,expected",
+ [
+ (10, 9, True),
+ (10, 10, False),
+ (10, 11, False), # a lowered cap refuses new seats, never revokes
+ (1, 0, True),
+ (1, 1, False),
+ ],
+)
+async def test_seat_is_free_only_below_the_cap(cap, taken, expected):
+ with patch.object(
+ capacity, "count_trial_seats", AsyncMock(return_value=taken)
+ ), patch.object(capacity, "_holds_seat", AsyncMock(return_value=False)):
+ assert await capacity.trial_seat_available(offer(cap)) is expected
+
+
+async def test_uncapped_offer_never_counts_seats():
+ """An uncapped trial must not pay for a COUNT on every status check."""
+ with patch.object(capacity, "count_trial_seats", AsyncMock()) as count:
+ assert await capacity.trial_seat_available(offer(None)) is True
+ count.assert_not_awaited()
+
+
+async def test_zero_cap_closes_enrolment_without_a_query():
+ with patch.object(
+ capacity, "count_trial_seats", AsyncMock()
+ ) as count, patch.object(capacity, "_holds_seat", AsyncMock(return_value=False)):
+ assert await capacity.trial_seat_available(offer(0)) is False
+ assert (
+ await capacity.trial_seat_available(offer(0), trial_id="expired-1") is False
+ )
+ count.assert_not_awaited()
+
+
+async def test_zero_cap_keeps_a_held_seat():
+ """Pausing enrolment must not strand someone already at the card screen."""
+ with patch.object(
+ capacity, "count_trial_seats", AsyncMock()
+ ) as count, patch.object(
+ capacity, "_holds_seat", AsyncMock(return_value=True)
+ ) as holds:
+ assert await capacity.trial_seat_available(offer(0), trial_id="trial-1") is True
+ count.assert_not_awaited()
+ assert holds.await_args.args[0] == "trial-1"
+
+
+async def test_a_held_seat_is_not_revoked_by_latecomers():
+ """Someone mid-checkout keeps their seat when the rest fill up."""
+ with patch.object(
+ capacity, "count_trial_seats", AsyncMock(return_value=10)
+ ) as count, patch.object(capacity, "_holds_seat", AsyncMock(return_value=True)):
+ assert (
+ await capacity.trial_seat_available(offer(10), trial_id="trial-1") is True
+ )
+ # counted the *others*, so the holder does not crowd itself out
+ assert count.await_args.kwargs["exclude_trial_id"] == "trial-1"
+
+
+async def test_full_trial_refuses_an_enrolment_holding_no_seat():
+ with patch.object(
+ capacity, "count_trial_seats", AsyncMock(return_value=10)
+ ), patch.object(capacity, "_holds_seat", AsyncMock(return_value=False)):
+ assert (
+ await capacity.trial_seat_available(offer(10), trial_id="expired-1")
+ is False
+ )
+
+
+async def test_seat_query_counts_running_trials_and_open_checkouts():
+ """The cap is meaningless if it ignores everyone at the card screen."""
+ with patch.object(
+ capacity, "query_raw_with_schema", AsyncMock(return_value=[])
+ ) as query:
+ assert await capacity.count_trial_seats() == 0
+ sql = query.await_args.args[0]
+ assert "'trialing'" in sql and '"cardVerifiedAt" IS NOT NULL' in sql
+ assert "'checkout_pending'" in sql and '"updatedAt"' in sql
+ # the reservation window is passed as a bound parameter, not interpolated
+ assert query.await_args.args[2] == (
+ f"{capacity.CHECKOUT_RESERVATION.total_seconds()} seconds"
+ )
+
+
+async def test_capacity_lock_is_one_global_key():
+ """Two enrolments must contend, or both read the same last free seat."""
+ tx = AsyncMock()
+ with patch.object(
+ capacity, "query_raw_with_schema", AsyncMock(return_value=[])
+ ) as query:
+ await capacity.lock_trial_capacity(tx)
+ assert "pg_advisory_xact_lock" in query.await_args.args[0]
+ assert query.await_args.args[1] == capacity._CAPACITY_LOCK
+
+
+async def test_renewal_without_a_cap_takes_no_lock():
+ with patch.object(capacity, "transaction") as tx:
+ assert await capacity.renew_trial_seat(offer(None), "trial-1") is True
+ tx.assert_not_called()
+
+
[email protected]("free", [True, False])
+async def test_renewal_checks_and_restarts_the_hold_under_the_lock(free):
+ """A returner is re-admitted atomically, or not at all."""
+ tx = AsyncMock()
+ calls: list[str] = []
+
+ async def lock(client):
+ assert client is tx
+ calls.append("lock")
+
+ async def seat(capped, *, trial_id, client):
+ assert (trial_id, client) == ("trial-1", tx)
+ calls.append("check")
+ return free
+
+ async def renew(sql, trial_id, *, client):
+ assert "checkout_pending" in sql and '"updatedAt" = NOW()' in sql
+ assert (trial_id, client) == ("trial-1", tx)
+ calls.append("renew")
+ return 1
+
+ transaction = MagicMock()
+ transaction.return_value.__aenter__.return_value = tx
+ with (
+ patch.object(capacity, "transaction", transaction),
+ patch.object(capacity, "lock_trial_capacity", lock),
+ patch.object(capacity, "trial_seat_available", seat),
+ patch.object(capacity, "execute_raw_with_schema", renew),
+ ):
+ assert await capacity.renew_trial_seat(offer(5), "trial-1") is free
+ assert calls == (["lock", "check", "renew"] if free else ["lock", "check"])
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_checkout.py b/autogpt_platform/backend/backend/data/subscription_trial_checkout.py
index 464f68baca..2b2f80690f 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_checkout.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_checkout.py
@@ -22,6 +22,11 @@ from backend.data.subscription_trial import (
get_subscription_trial,
reserve_subscription_trial,
)
+from backend.data.subscription_trial_capacity import (
+ TRIAL_FULL,
+ TrialCapacityReached,
+ renew_trial_seat,
+)
from backend.data.subscription_trial_config import (
AcceptedTrialOffer,
TrialOffer,
@@ -50,10 +55,12 @@ async def create_trial_checkout(
success_url: str,
cancel_url: str,
metadata: dict[str, str],
+ *,
+ country: str | None = None,
) -> str:
async with subscription_checkout_lock(user_id):
return await _create_trial_checkout(
- user_id, offer_token, success_url, cancel_url, metadata
+ user_id, offer_token, success_url, cancel_url, metadata, country
)
@@ -63,8 +70,12 @@ async def _create_trial_checkout(
success_url: str,
cancel_url: str,
metadata: dict[str, str],
+ country: str | None,
) -> str:
- offer = await get_trial_offer(user_id)
+ # The same question the status endpoint answers before showing the offer,
+ # asked of the *current* flag: someone who would not be shown the trial
+ # now cannot start or resume one, whatever they were shown earlier.
+ offer = await get_trial_offer(user_id, country=country)
if offer is None:
raise TrialUnavailable("Trials are not available right now")
existing = await get_subscription_trial(user_id)
@@ -73,6 +84,8 @@ async def _create_trial_checkout(
raise TrialUnavailable("A trial has already been used for this account")
if existing.offer.token != offer_token:
raise TrialUnavailable("Refresh to accept the reserved trial terms")
+ if not await renew_trial_seat(offer, existing.id):
+ raise TrialUnavailable(TRIAL_FULL)
return await _resume_checkout(existing)
customer_id = await get_stripe_customer_id(user_id)
await _verify_eligibility(user_id, customer_id, offer)
@@ -81,9 +94,12 @@ async def _create_trial_checkout(
raise TrialUnavailable(
"The trial offer changed. Refresh to see the current terms"
)
- trial = await reserve_subscription_trial(
- user_id, accepted, customer_id, success_url, cancel_url, metadata
- )
+ try:
+ trial = await reserve_subscription_trial(
+ user_id, accepted, customer_id, success_url, cancel_url, metadata
+ )
+ except TrialCapacityReached as exc:
+ raise TrialUnavailable(str(exc)) from exc
if trial.offer.token != offer_token:
raise TrialUnavailable(
"Another checkout reserved different trial terms. Refresh"
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py b/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py
index 652454dfc6..2eca8b8763 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_checkout_test.py
@@ -221,3 +221,115 @@ def test_paid_conversion_requires_paid_post_trial_invoice(
}
)
assert trial_subscription_tier(trial, subscription, now) == expected
+
+
+async def test_full_trial_surfaces_as_a_retryable_checkout_failure(
+ trial, checkout_guard
+):
+ """A full trial must reach the client as the 409 the route maps, not a 500."""
+ with (
+ patch.object(checkout, "get_trial_offer", AsyncMock(return_value=trial.offer)),
+ patch.object(checkout, "get_subscription_trial", AsyncMock(return_value=None)),
+ patch.object(
+ checkout, "get_stripe_customer_id", AsyncMock(return_value="cus_1")
+ ),
+ patch.object(checkout, "_verify_eligibility", AsyncMock()),
+ patch.object(
+ checkout, "resolve_trial_price", AsyncMock(return_value=trial.offer)
+ ),
+ patch.object(
+ checkout,
+ "reserve_subscription_trial",
+ AsyncMock(side_effect=checkout.TrialCapacityReached("The trial is full")),
+ ),
+ patch.object(checkout, "_resume_checkout", AsyncMock()) as resume,
+ ):
+ with pytest.raises(checkout.TrialUnavailable, match="full"):
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ )
+ resume.assert_not_awaited()
+
+
+async def test_checkout_asks_the_flag_with_the_visitors_country(trial, checkout_guard):
+ with (
+ patch.object(
+ checkout, "get_trial_offer", AsyncMock(return_value=None)
+ ) as offer,
+ patch.object(checkout, "get_stripe_customer_id", AsyncMock()) as customer,
+ ):
+ with pytest.raises(checkout.TrialUnavailable, match="not available"):
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ country="IN",
+ )
+ assert offer.await_args.kwargs["country"] == "IN"
+ customer.assert_not_awaited()
+
+
+async def test_excluded_visitor_cannot_resume_a_pending_checkout(trial, checkout_guard):
+ """The current flag decides, even for someone who reserved while eligible."""
+ with (
+ patch.object(checkout, "get_trial_offer", AsyncMock(return_value=None)),
+ patch.object(checkout, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(checkout, "_resume_checkout", AsyncMock()) as resume,
+ ):
+ with pytest.raises(checkout.TrialUnavailable, match="not available"):
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ country="IN",
+ )
+ resume.assert_not_awaited()
+
+
[email protected]("seat,resumed", [(True, True), (False, False)])
+async def test_resume_is_checked_against_the_current_cap(
+ trial, checkout_guard, seat, resumed
+):
+ """The live cap applies, not the one pinned on the enrolment."""
+ capped = trial.offer.model_copy(update={"max_active_trials": 10})
+ with (
+ patch.object(checkout, "get_trial_offer", AsyncMock(return_value=capped)),
+ patch.object(checkout, "get_subscription_trial", AsyncMock(return_value=trial)),
+ patch.object(
+ checkout, "renew_trial_seat", AsyncMock(return_value=seat)
+ ) as check,
+ patch.object(
+ checkout, "_resume_checkout", AsyncMock(return_value="https://x")
+ ) as resume,
+ ):
+ if resumed:
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ )
+ else:
+ with pytest.raises(checkout.TrialUnavailable, match="full"):
+ await checkout.create_trial_checkout(
+ trial.user_id,
+ trial.offer.token,
+ trial.success_url,
+ trial.cancel_url,
+ {},
+ )
+ assert check.await_args.args == (capped, trial.id)
+ assert resume.await_count == int(resumed)
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_config.py b/autogpt_platform/backend/backend/data/subscription_trial_config.py
index 1413853929..a8885d5ba2 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_config.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_config.py
@@ -14,6 +14,7 @@ from pydantic import (
model_validator,
)
+from backend.util.country import country_code
from backend.util.feature_flag import Flag, get_feature_flag_value, is_feature_enabled
logger = logging.getLogger(__name__)
@@ -33,6 +34,11 @@ class TrialOffer(BaseModel):
onboarding_credit_amount: int = Field(ge=0, le=2_147_483_647, strict=True)
allow_existing_beta_users: bool = Field(default=False, strict=True)
+ # Omit (or null) to run the trial uncapped. 0 closes enrolment without
+ # ending the trials already running: the cap is only ever consulted when
+ # a new seat is taken, never to revoke a seat already held.
+ max_active_trials: int | None = Field(default=None, ge=0, strict=True)
+
@model_validator(mode="after")
def ordered_limits(self) -> "TrialOffer":
if not self.daily_cost_limit <= self.weekly_cost_limit <= self.total_cost_limit:
@@ -58,17 +64,47 @@ class AcceptedTrialOffer(TrialOffer):
@property
def token(self) -> str:
- return sha256(self.model_dump_json().encode()).hexdigest()
-
-
-async def get_trial_offer(user_id: str) -> TrialOffer | None:
+ """A hash of the terms the user is shown and accepts at checkout.
+
+ The cap is our capacity setting, not one of those terms, so it is left
+ out: changing it must not bounce everyone mid-checkout with "the offer
+ changed", and an offer hashes exactly as it did before the cap existed.
+ """
+ terms = self.model_dump_json(exclude={"max_active_trials"})
+ return sha256(terms.encode()).hexdigest()
+
+
+async def get_trial_offer(
+ user_id: str, *, country: str | None = None
+) -> TrialOffer | None:
+ """The trial this user may see right now, or None.
+
+ Who is offered a trial is the flag's targeting, not this code: the
+ country is handed to the flag as the ``country`` attribute so that rules
+ such as "country is not one of IN" decide it. A missing country never
+ matches a country rule, negated or not, so the recommended shape -- a
+ rule serving the offer when country is not one of the excluded list,
+ falling through to off -- also withholds it when the country is unknown.
+
+ A country that is present but not an assigned ISO 3166-1 alpha-2 code is
+ refused outright rather than handed on: under a negated rule any value
+ other than the excluded ones -- ``"IN, US"`` from a duplicated header, say
+ -- would be served the offer, so it fails closed instead.
+ """
+ code = country_code(country)
+ if code is None and (country or "").strip():
+ logger.info("Unrecognised client country; withholding the trial offer")
+ return None
try:
if not await is_feature_enabled(
Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False
):
return None
raw = await get_feature_flag_value(
- Flag.CARD_REQUIRED_TRIAL_OFFER, user_id, None
+ Flag.CARD_REQUIRED_TRIAL_OFFER,
+ user_id,
+ None,
+ attributes={"country": code} if code else None,
)
# The flag's disabled variation is an object ({"enabled": false}), not
# null, so only a payload claiming to be an offer is worth an error.
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_config_test.py b/autogpt_platform/backend/backend/data/subscription_trial_config_test.py
index d4d00436d5..dfd5704dde 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_config_test.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_config_test.py
@@ -4,6 +4,9 @@ from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock, patch
import pytest
+from ldclient import Context, LDClient
+from ldclient.config import Config
+from ldclient.integrations.test_data import TestData
from pydantic import ValidationError
from backend.data import subscription_trial_config as trials
@@ -68,6 +71,9 @@ def test_offer_has_no_implicit_existing_user_eligibility():
{"allow_existing_beta_users": "true"},
{"version": ""},
{"unknown_setting": 1},
+ {"max_active_trials": -1},
+ {"max_active_trials": "5"},
+ {"max_active_trials": True},
],
)
def test_rejects_invalid_or_ambiguous_offer(overrides):
@@ -184,6 +190,98 @@ async def test_payment_enabled_and_valid_offer_is_available():
)
+def test_offer_without_a_cap_keeps_its_old_meaning():
+ """Offers written before the cap existed validate and stay uncapped."""
+ assert trials.TrialOffer.model_validate(offer_data()).max_active_trials is None
+
+
+def test_zero_cap_is_expressible_and_distinct_from_absent():
+ """0 pauses enrolment; absent means uncapped. They must not collapse."""
+ paused = trials.TrialOffer.model_validate({**offer_data(), "max_active_trials": 0})
+ assert paused.max_active_trials == 0
+
+
+ "country,attributes",
+ [
+ ("IN", {"country": "IN"}),
+ (" in ", {"country": "IN"}),
+ (None, None),
+ # a blank header is an unknown country, not a known non-excluded one
+ ("", None),
+ (" ", None),
+ ],
+)
+async def test_country_is_handed_to_the_flag_not_decided_here(country, attributes):
+ """Who sees a trial is the flag's targeting; the code only supplies the fact."""
+ with patch.object(
+ trials, "is_feature_enabled", AsyncMock(return_value=True)
+ ), patch.object(
+ trials, "get_feature_flag_value", AsyncMock(return_value=offer_data())
+ ) as flag:
+ await trials.get_trial_offer("user-1", country=country)
+ assert flag.await_args.kwargs["attributes"] == attributes
+
+
+ "country",
+ # a duplicated header comma-joined, unassigned and reserved codes, a name
+ ["IN, US", "US,IN", "XX", "ZZ", "EU", "T1", "INDIA", "U S", "us\u200b"],
+)
+async def test_a_country_that_is_not_an_iso_code_never_reaches_the_flag(country):
+ with patch.object(
+ trials, "is_feature_enabled", AsyncMock(return_value=True)
+ ), patch.object(
+ trials, "get_feature_flag_value", AsyncMock(return_value=offer_data())
+ ) as flag:
+ assert await trials.get_trial_offer("user-1", country=country) is None
+ flag.assert_not_awaited()
+
+
+ "country,offered",
+ [
+ ("US", True),
+ (" gb ", True),
+ ("IN", False),
+ (None, False),
+ # junk must not satisfy "country is not one of IN"
+ ("IN, US", False),
+ ("XX", False),
+ ("India", False),
+ ],
+)
+async def test_the_recommended_rule_fails_closed_through_the_real_evaluator(
+ country, offered
+):
+ """The production rule shape, evaluated by LaunchDarkly's own SDK."""
+ td = TestData.data_source()
+ td.update(
+ td.flag(trials.Flag.CARD_REQUIRED_TRIAL_OFFER.value)
+ .variations({"enabled": False}, offer_data())
+ .fallthrough_variation(0)
+ .if_not_match("country", "IN")
+ .then_return(1)
+ )
+ client = LDClient(Config("sdk-test", update_processor_class=td, send_events=False))
+ try:
+ with patch.object(
+ trials, "is_feature_enabled", AsyncMock(return_value=True)
+ ), patch("backend.util.feature_flag.ldclient.get", return_value=client), patch(
+ "backend.util.feature_flag._fetch_user_context_status",
+ AsyncMock(
+ return_value=(Context.builder("user-1").kind("user").build(), True)
+ ),
+ ):
+ offer = await trials.get_trial_offer("user-1", country=country)
+ finally:
+ client.close()
+ assert (offer is not None) is offered
+
+
@pytest.mark.parametrize(
"flag_value",
[{"enabled": False}, {"enabled": True}, {}, None, False],
@@ -196,7 +294,7 @@ async def test_flag_value_that_is_not_an_offer_is_silent(flag_value):
), patch.object(
trials, "get_feature_flag_value", AsyncMock(return_value=flag_value)
), captured_logs() as records:
- assert await trials.get_trial_offer("user-1") is None
+ assert await trials.get_trial_offer("user-1", country="IN") is None
assert [r for r in records if r.levelno >= logging.WARNING] == []
assert [r.getMessage() for r in records] == [
@@ -218,3 +316,38 @@ async def test_offer_that_fails_validation_is_still_an_error():
errors = [r for r in records if r.levelno >= logging.ERROR]
assert len(errors) == 1
assert "Invalid card-required-trial-offer" in errors[0].getMessage()
+
+
+# The live production offer variation, verbatim from LaunchDarkly, and the
+# token dev computes for it before the cap existed.
+LIVE_OFFER = {
+ "allow_existing_beta_users": False,
+ "billing_cycle": "monthly",
+ "daily_cost_limit": 3125000,
+ "duration_days": 7,
+ "new_users_from": "2026-09-06T00:00:00Z",
+ "onboarding_credit_amount": 300,
+ "tier": "PRO",
+ "total_cost_limit": 31250000,
+ "version": "pro-equivalent-v1",
+ "weekly_cost_limit": 15625000,
+ "price_id": "price_live",
+ "unit_amount": 5000,
+ "currency": "usd",
+}
+DEV_TOKEN = "8e7acb63affd0d9ecc34e906a6c4f0fee8c139a1e57431881f83de455aa6a49f"
+
+
[email protected]("cap", [None, 0, 500])
+def test_the_cap_never_moves_the_offer_token(cap):
+ """Deploying the cap, or changing it, must not invalidate a shown offer.
+
+ The token gates checkout: a mismatch refuses it with "the offer changed".
+ """
+ offer = {**LIVE_OFFER, **({} if cap is None else {"max_active_trials": cap})}
+ assert trials.AcceptedTrialOffer.model_validate(offer).token == DEV_TOKEN
+
+
+def test_a_real_term_still_moves_the_offer_token():
+ changed = {**LIVE_OFFER, "duration_days": 14}
+ assert trials.AcceptedTrialOffer.model_validate(changed).token != DEV_TOKEN
diff --git a/autogpt_platform/backend/backend/util/country.py b/autogpt_platform/backend/backend/util/country.py
new file mode 100644
index 0000000000..5a658110c3
--- /dev/null
+++ b/autogpt_platform/backend/backend/util/country.py
@@ -0,0 +1,40 @@
+"""ISO 3166-1 alpha-2 country codes."""
+
+# The officially assigned codes (249). User-assigned and reserved codes such as
+# XK, EU, T1 or ZZ are deliberately absent: they name no country a rule can
+# be written for.
+ISO_3166_ALPHA2 = frozenset(
+ """
+ AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ
+ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ
+ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ
+ DE DJ DK DM DO DZ
+ EC EE EG EH ER ES ET
+ FI FJ FK FM FO FR
+ GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY
+ HK HM HN HR HT HU
+ ID IE IL IM IN IO IQ IR IS IT
+ JE JM JO JP
+ KE KG KH KI KM KN KP KR KW KY KZ
+ LA LB LC LI LK LR LS LT LU LV LY
+ MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
+ NA NC NE NF NG NI NL NO NP NR NU NZ
+ OM
+ PA PE PF PG PH PK PL PM PN PR PS PT PW PY
+ QA
+ RE RO RS RU RW
+ SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ
+ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ
+ UA UG UM US UY UZ
+ VA VC VE VG VI VN VU
+ WF WS
+ YE YT
+ ZA ZM ZW
+ """.split()
+)
+
+
+def country_code(value: str | None) -> str | None:
+ """*value* as an assigned ISO 3166-1 alpha-2 code, or None if it is not one."""
+ code = (value or "").strip().upper()
+ return code if code in ISO_3166_ALPHA2 else None
diff --git a/autogpt_platform/backend/backend/util/country_test.py b/autogpt_platform/backend/backend/util/country_test.py
new file mode 100644
index 0000000000..347b164a87
--- /dev/null
+++ b/autogpt_platform/backend/backend/util/country_test.py
@@ -0,0 +1,27 @@
+import pytest
+
+from backend.util.country import ISO_3166_ALPHA2, country_code
+
+
+def test_every_assigned_code_and_nothing_else():
+ assert len(ISO_3166_ALPHA2) == 249
+ assert {"US", "GB", "IN", "DE", "SS", "BQ"} <= ISO_3166_ALPHA2
+
+
+ "value,expected",
+ [
+ ("US", "US"),
+ (" in ", "IN"),
+ (None, None),
+ ("", None),
+ ("IN, US", None),
+ ("USA", None),
+ ("XK", None),
+ ("ZZ", None),
+ ("EU", None),
+ ("T1", None),
+ ],
+)
+def test_country_code_accepts_only_assigned_codes(value, expected):
+ assert country_code(value) == expected
diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.py
index aeea0f1437..fa74637d76 100644
--- a/autogpt_platform/backend/backend/util/feature_flag.py
+++ b/autogpt_platform/backend/backend/util/feature_flag.py
@@ -315,6 +315,19 @@ async def _fetch_user_context_status(user_id: str) -> tuple[Context, bool]:
return _anonymous_context(user_id), False
+def _with_request_attributes(context: Context, attributes: dict[str, str]) -> Context:
+ """*context* plus facts known only for this request, such as the country.
+
+ The user context is cached for a day, so anything that can change between
+ requests has to be layered on per evaluation rather than baked into it.
+ A copy is returned; the cached context is never modified. ``key`` and
+ ``kind`` are identity and cannot be overridden this way.
+ """
+ merged = {**context.to_dict(), **attributes}
+ merged.update(key=context.key, kind=context.kind)
+ return Context.from_dict(merged)
+
+
def _anonymous_context(user_id: str) -> Context:
"""Build a minimal anonymous LD context carrying only the user key."""
return Context.builder(user_id).kind("user").anonymous(True).build()
@@ -366,6 +379,8 @@ async def get_feature_flag_value(
flag_key: str,
user_id: str,
default: Any = None,
+ *,
+ attributes: dict[str, str] | None = None,
) -> Any:
"""
Get the raw value of a feature flag for a user.
@@ -381,12 +396,18 @@ async def get_feature_flag_value(
Returns:
The flag value from LaunchDarkly
"""
- value, _ = await _evaluate_flag_value(flag_key, user_id, default)
+ value, _ = await _evaluate_flag_value(
+ flag_key, user_id, default, attributes=attributes
+ )
return value
async def _evaluate_flag_value(
- flag_key: str, user_id: str, default: Any = None
+ flag_key: str,
+ user_id: str,
+ default: Any = None,
+ *,
+ attributes: dict[str, str] | None = None,
) -> tuple[Any, bool]:
"""``(value, evaluated)`` for one raw flag read.
@@ -408,6 +429,8 @@ async def _evaluate_flag_value(
# Get user context (role/email) from the Better Auth user table
context, context_resolved = await _fetch_user_context_status(user_id)
+ if attributes:
+ context = _with_request_attributes(context, attributes)
# Evaluate flag
result = client.variation(flag_key, context, default)
diff --git a/autogpt_platform/backend/backend/util/feature_flag_test.py b/autogpt_platform/backend/backend/util/feature_flag_test.py
index 66f4aaa495..ebdb97bcf6 100644
--- a/autogpt_platform/backend/backend/util/feature_flag_test.py
+++ b/autogpt_platform/backend/backend/util/feature_flag_test.py
@@ -7,6 +7,8 @@ from pathlib import Path
import pytest
from fastapi import HTTPException
from ldclient import Context, LDClient
+from ldclient.config import Config
+from ldclient.integrations.test_data import TestData
import backend.util.feature_flag as feature_flag_module
from backend.util.feature_flag import (
@@ -935,3 +937,85 @@ class TestEvaluateFeatureFlag:
assert await is_feature_enabled(Flag.HIRE_EXPERTS, "u-1") is True
ld_client.variation.side_effect = Exception("boom")
assert await is_feature_enabled(Flag.HIRE_EXPERTS, "u-1") is False
+
+
+class TestRequestAttributes:
+ """Facts known only per request (the visitor's country) reach targeting."""
+
+ @pytest.mark.asyncio
+ async def test_attributes_are_layered_on_without_touching_the_cache(
+ self, ld_client, mocker
+ ):
+ cached = (
+ Context.builder("user-1")
+ .kind("user")
+ .set("email_domain", "agpt.co")
+ .build()
+ )
+ mocker.patch(
+ "backend.util.feature_flag._fetch_user_context_status",
+ return_value=(cached, True),
+ )
+ ld_client.variation.return_value = {"version": "v1"}
+
+ await feature_flag_module.get_feature_flag_value(
+ "card-required-trial-offer", "user-1", None, attributes={"country": "IN"}
+ )
+
+ evaluated = ld_client.variation.call_args[0][1]
+ assert evaluated.get("country") == "IN"
+ assert evaluated.get("email_domain") == "agpt.co"
+ assert cached.get("country") is None
+
+ @pytest.mark.asyncio
+ async def test_attributes_cannot_change_who_is_evaluated(self, ld_client, mocker):
+ cached = Context.builder("user-1").kind("user").build()
+ mocker.patch(
+ "backend.util.feature_flag._fetch_user_context_status",
+ return_value=(cached, True),
+ )
+ await feature_flag_module.get_feature_flag_value(
+ "f", "user-1", None, attributes={"key": "someone-else", "kind": "org"}
+ )
+ evaluated = ld_client.variation.call_args[0][1]
+ assert (evaluated.key, evaluated.kind) == ("user-1", "user")
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "country,offered", [("US", True), ("BR", True), ("IN", False), (None, False)]
+ )
+ async def test_a_real_country_rule_decides_the_offer(
+ self, mocker, country, offered
+ ):
+ """End to end through the real SDK evaluator, not a mocked variation.
+
+ The recommended production shape: serve the offer when country is not
+ one of the excluded list; otherwise, including an unknown country,
+ fall through to off.
+ """
+ td = TestData.data_source()
+ td.update(
+ td.flag("card-required-trial-offer")
+ .variations({"enabled": False}, {"version": "v1"})
+ .fallthrough_variation(0)
+ .if_not_match("country", "IN")
+ .then_return(1)
+ )
+ client = LDClient(
+ Config("sdk-test", update_processor_class=td, send_events=False)
+ )
+ mocker.patch("backend.util.feature_flag.ldclient.get", return_value=client)
+ mocker.patch(
+ "backend.util.feature_flag._fetch_user_context_status",
+ return_value=(Context.builder("user-1").kind("user").build(), True),
+ )
+ try:
+ value = await feature_flag_module.get_feature_flag_value(
+ "card-required-trial-offer",
+ "user-1",
+ None,
+ attributes={"country": country} if country else None,
+ )
+ finally:
+ client.close()
+ assert (value == {"version": "v1"}) is offered
diff --git a/autogpt_platform/backend/scripts/feature_flag_sync.py b/autogpt_platform/backend/scripts/feature_flag_sync.py
index 176002afea..58fb806228 100644
--- a/autogpt_platform/backend/scripts/feature_flag_sync.py
+++ b/autogpt_platform/backend/scripts/feature_flag_sync.py
@@ -21,7 +21,12 @@ from pydantic import BaseModel
# What `_person_properties` in `backend.util.feature_flag` sends for a user;
# the SDK adds `distinct_id` (the user id, LaunchDarkly's context key) itself.
-PERSON_PROPERTIES = frozenset({"email", "email_domain", "role", "created_at"})
+# `country` is not stored on the person: it is the visitor's ISO country code,
+# passed per evaluation by callers that know it (the trial offer, from the
+# country token the proxy signs), so it is absent whenever a caller does not.
+PERSON_PROPERTIES = frozenset(
+ {"email", "email_domain", "role", "created_at", "country"}
+)
ATTRIBUTE_ALIASES = {
"/custom/role": "role",
"custom.role": "role",
@@ -336,7 +341,7 @@ def _segment_groups(
if any(c.get("op") == "segmentMatch" for c in clauses):
raise Unmappable("segment rule references another segment")
if _reachable(clauses, notes):
- groups.append([_clause_property(c) for c in clauses])
+ groups.append([p for c in clauses for p in _clause_properties(c)])
if excluded:
groups = [g + [_person("distinct_id", "is_not", excluded)] for g in groups]
return groups
@@ -425,10 +430,10 @@ def _rule_groups(
clauses: list[dict[str, Any]], cohorts: dict[str, MappedCohort]
) -> list[list[dict[str, Any]]]:
"""A rule's clauses as condition groups: AND within, a segment list fans out into OR."""
- alternatives: list[list[dict[str, Any]]] = []
+ alternatives: list[list[list[dict[str, Any]]]] = []
for clause in clauses:
if clause.get("op") != "segmentMatch":
- alternatives.append([_clause_property(clause)])
+ alternatives.append([_clause_properties(clause)])
continue
if clause.get("negate"):
raise Unmappable("negated segment match")
@@ -441,13 +446,31 @@ def _rule_groups(
raise Unmappable(f"references segment `{seg}`, which needs a decision")
if cohort.payload is not None:
options.append(
- {"key": "id", "type": "cohort", "value": cohort_name(seg)}
+ [{"key": "id", "type": "cohort", "value": cohort_name(seg)}]
)
# A rule naming only empty segments matches nobody.
if not options:
return []
alternatives.append(options)
- return [list(combo) for combo in itertools.product(*alternatives)]
+ return [
+ [prop for option in combo for prop in option]
+ for combo in itertools.product(*alternatives)
+ ]
+
+
+def _clause_properties(clause: dict[str, Any]) -> list[dict[str, Any]]:
+ """One LaunchDarkly clause as PostHog properties, all of which must hold.
+
+ A negated LaunchDarkly clause never matches a context that lacks the
+ attribute: "country is not one of IN" serves nothing to a visitor with no
+ country. PostHog's negated operators promise nothing about a missing
+ property, so the property is required to be set as well -- otherwise the
+ port would widen who is served exactly where the attribute is unknown.
+ """
+ prop = _clause_property(clause)
+ if clause.get("negate"):
+ return [_person(prop["key"], "is_set", "is_set"), prop]
+ return [prop]
def _clause_property(clause: dict[str, Any]) -> dict[str, Any]:
diff --git a/autogpt_platform/backend/scripts/feature_flag_sync_test.py b/autogpt_platform/backend/scripts/feature_flag_sync_test.py
index 3572ac5775..6477fb0493 100644
--- a/autogpt_platform/backend/scripts/feature_flag_sync_test.py
+++ b/autogpt_platform/backend/scripts/feature_flag_sync_test.py
@@ -232,6 +232,57 @@ def test_off_boolean_flag_serves_its_off_variation_to_everyone(off_variation, ac
assert _served(payload)("user-x", ADMIN) is active
+ "clause",
+ [
+ {"attribute": "country", "op": "in", "values": ["IN"], "negate": True},
+ {"attribute": "country", "op": "endsWith", "values": ["N"], "negate": True},
+ ],
+)
+def test_negated_clause_never_serves_a_user_without_the_attribute(clause):
+ """LaunchDarkly: a missing attribute matches no clause, negated or not.
+
+ The trial offer's production rule is "country is not one of IN". Without
+ the is_set guard, PostHog would be free to serve it to a visitor whose
+ country is unknown -- the one case LaunchDarkly withholds it.
+ """
+ flag = _flag("boolean", rules=[_rule([clause], 0)], fallthrough=1)
+
+ mapped = map_flag(flag, ENV, _cohorts())
+
+ assert mapped.decisions == []
+ served = _served(mapped.payload)
+ assert served("user-x", {"country": "US"}) is True
+ assert served("user-x", {"country": "IN"}) is False
+ # The local evaluator defers to PostHog's servers here, and the group it
+ # defers with can only match once country is set.
+ group = _payload(mapped)["filters"]["groups"][0]["properties"]
+ assert {
+ "key": "country",
+ "type": "person",
+ "operator": "is_set",
+ "value": "is_set",
+ } in group
+
+
+def test_country_rule_ports_instead_of_needing_a_decision():
+ """The trial offer's country targeting must survive the migration."""
+ flag = _flag(
+ "boolean",
+ rules=[
+ _rule([{"attribute": "country", "op": "in", "values": ["US", "GB"]}], 0)
+ ],
+ fallthrough=1,
+ )
+
+ mapped = map_flag(flag, ENV, _cohorts())
+
+ assert mapped.decisions == []
+ served = _served(mapped.payload)
+ assert served("user-x", {"country": "GB"}) is True
+ assert served("user-x", {"country": "IN"}) is False
+
+
def test_multivariate_flag_serves_launchdarkly_values_as_payloads():
flag = _flag(
"multivariate",
@@ -319,7 +370,7 @@ def test_target_on_a_context_kind_no_client_sends_is_dropped_with_a_note():
"rules": [
{
"clauses": [
- {"attribute": "country", "op": "in", "values": ["NL"]}
+ {"attribute": "plan", "op": "in", "values": ["pro"]}
],
"variation": 0,
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index af02499a01..15ea5d24e7 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -5956,6 +5956,14 @@
},
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
}
}
},
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
index 9b97faf58b..9532bce787 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
@@ -5,12 +5,17 @@ vi.mock("@/lib/auth/server/getServerAuthToken", () => ({
getServerAuthToken: vi.fn(),
}));
+vi.mock("@/lib/auth/country-token", () => ({
+ getCountryToken: vi.fn(),
+}));
+
vi.mock("@/services/environment", () => ({
environment: {
getAGPTServerBaseUrl: vi.fn(() => "https://backend.test"),
},
}));
+import { getCountryToken } from "@/lib/auth/country-token";
import { getServerAuthToken } from "@/lib/auth/server/getServerAuthToken";
import { GET, POST } from "../route";
@@ -23,6 +28,10 @@ function makeParams(path: string[]) {
describe("proxy route — handler pass-through", () => {
beforeEach(() => {
vi.mocked(getServerAuthToken).mockResolvedValue("test-token");
+ vi.mocked(getCountryToken).mockReset();
+ vi.mocked(getCountryToken).mockImplementation(
+ async (country) => `signed-${country}`,
+ );
vi.stubGlobal("fetch", vi.fn());
});
@@ -215,6 +224,68 @@ describe("proxy route — handler pass-through", () => {
expect(sentHeaders.get("x-datafast-session-id")).toBe("session-456");
});
+ it("sends the edge-observed country only as a signed token", async () => {
+ vi.mocked(fetch).mockResolvedValue(
+ new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {
+ headers: { "x-vercel-ip-country": "DE" },
+ });
+ await GET(req, makeParams(["api", "v1", "items"]));
+
+ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;
+ expect(getCountryToken).toHaveBeenCalledWith("DE");
+ expect(sentHeaders.get("x-client-country-token")).toBe("signed-DE");
+ expect(sentHeaders.get("x-client-country")).toBeNull();
+ expect(sentHeaders.get("x-vercel-ip-country")).toBeNull();
+ });
+
+ it("drops a browser-supplied country, plain or tokenised", async () => {
+ vi.mocked(fetch).mockResolvedValue(
+ new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {
+ headers: {
+ "x-client-country": "US",
+ "x-client-country-token": "forged",
+ },
+ });
+ await GET(req, makeParams(["api", "v1", "items"]));
+
+ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;
+ expect(sentHeaders.get("x-client-country")).toBeNull();
+ expect(sentHeaders.get("x-client-country-token")).toBeNull();
+ expect(getCountryToken).not.toHaveBeenCalled();
+ });
+
+ it("still proxies, without a country, when signing fails", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.mocked(getCountryToken).mockRejectedValueOnce(new Error("no jwks"));
+ vi.mocked(fetch).mockResolvedValue(
+ new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ const req = new NextRequest("https://app.test/api/proxy/api/v1/items", {
+ headers: { "x-vercel-ip-country": "DE" },
+ });
+ const res = await GET(req, makeParams(["api", "v1", "items"]));
+
+ expect(res.status).toBe(200);
+ const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;
+ expect(sentHeaders.get("x-client-country-token")).toBeNull();
+ });
+
it("omits Authorization header when no token is available", async () => {
vi.mocked(getServerAuthToken).mockResolvedValueOnce(null);
vi.mocked(fetch).mockResolvedValue(
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
index 3f6fae236b..3bfd19b47b 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
@@ -1,7 +1,10 @@
import {
API_KEY_HEADER_NAME,
+ CLIENT_COUNTRY_TOKEN_HEADER_NAME,
IMPERSONATION_HEADER_NAME,
+ VERCEL_COUNTRY_HEADER_NAME,
} from "@/lib/constants";
+import { getCountryToken } from "@/lib/auth/country-token";
import { getServerAuthToken } from "@/lib/auth/server/getServerAuthToken";
import { environment } from "@/services/environment";
import { NextRequest, NextResponse } from "next/server";
@@ -83,13 +86,31 @@ function buildBackendUrl(path: string[], queryString: string): string {
return `${environment.getAGPTServerBaseUrl()}/${path.join("/")}${queryString}`;
}
-function buildForwardHeaders(req: NextRequest, token: string | null): Headers {
+async function signCountry(country: string) {
+ try {
+ return await getCountryToken(country);
+ } catch (error) {
+ console.error("[proxy] Could not sign the client country", error);
+ return null;
+ }
+}
+
+async function buildForwardHeaders(
+ req: NextRequest,
+ token: string | null,
+): Promise<Headers> {
const headers = new Headers();
for (const name of FORWARDED_REQUEST_HEADERS) {
const value = req.headers.get(name);
if (value) headers.set(name, value);
}
headers.set("accept-encoding", BACKEND_ACCEPT_ENCODING);
+ // The visitor's country as the edge saw it, signed so the backend can tell
+ // it from one a caller typed. Without it the country is unknown, which the
+ // trial offer treats as "no offer", so a failed mint fails closed.
+ const country = req.headers.get(VERCEL_COUNTRY_HEADER_NAME);
+ const countryToken = country ? await signCountry(country) : null;
+ if (countryToken) headers.set(CLIENT_COUNTRY_TOKEN_HEADER_NAME, countryToken);
if (token) {
headers.set("authorization", `Bearer ${token}`);
}
@@ -206,7 +227,7 @@ async function handler(
return await handleWorkspaceDownload(backendUrl, token);
}
- const headers = buildForwardHeaders(req, token);
+ const headers = await buildForwardHeaders(req, token);
const hasBody = !METHODS_WITHOUT_BODY.has(method);
// Two-phase timeout: the overall ceiling covers the whole hop, while the
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/country-token.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/country-token.test.ts
new file mode 100644
index 0000000000..50e750e740
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/country-token.test.ts
@@ -0,0 +1,53 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mintServiceTokenMock = vi.fn();
+vi.mock("../service-token", () => ({
+ mintServiceToken: (...args: unknown[]) => mintServiceTokenMock(...args),
+}));
+
+import { CLIENT_COUNTRY_SCOPE, getCountryToken } from "../country-token";
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ mintServiceTokenMock.mockReset();
+ mintServiceTokenMock.mockImplementation(
+ async (_scope: string, claims: { country: string }) =>
+ `signed-${claims.country}-${Date.now()}`,
+ );
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("getCountryToken", () => {
+ it("signs the normalised country under the client-country scope", async () => {
+ vi.setSystemTime(1_000_000);
+
+ const token = await getCountryToken(" de ");
+
+ expect(token).toBe("signed-DE-1000000");
+ expect(mintServiceTokenMock).toHaveBeenCalledWith(CLIENT_COUNTRY_SCOPE, {
+ country: "DE",
+ });
+ });
+
+ it("reuses a token for 30 seconds, then mints a fresh one", async () => {
+ vi.setSystemTime(2_000_000);
+ const first = await getCountryToken("FR");
+
+ vi.setSystemTime(2_000_000 + 29_000);
+ expect(await getCountryToken("FR")).toBe(first);
+
+ vi.setSystemTime(2_000_000 + 30_000);
+ expect(await getCountryToken("FR")).not.toBe(first);
+ expect(mintServiceTokenMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("signs nothing that is not a two-letter code", async () => {
+ for (const junk of ["IN, US", "", "IND", "1N"]) {
+ expect(await getCountryToken(junk)).toBeNull();
+ }
+ expect(mintServiceTokenMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/service-token.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/service-token.test.ts
index e9b58d36b0..d2b3a60454 100644
--- a/autogpt_platform/frontend/src/lib/auth/__tests__/service-token.test.ts
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/service-token.test.ts
@@ -58,4 +58,22 @@ describe("mintServiceToken", () => {
const [, config] = signJWTMock.mock.calls[0] as [unknown, CapturedSignArgs];
expect(config.options.jwks.keyPairConfig.alg).toBe("ES256");
});
+
+ it("adds vouched claims without letting them override the token's identity", async () => {
+ await mintServiceToken("client-country", {
+ country: "DE",
+ sub: "user-1",
+ aud: "authenticated",
+ scope: "admin",
+ });
+
+ const [, config] = signJWTMock.mock.calls[0] as [
+ unknown,
+ CapturedSignArgs & { payload: { country: string } },
+ ];
+ expect(config.payload.country).toBe("DE");
+ expect(config.payload.sub).toBe(FRONTEND_SERVICE_SUBJECT);
+ expect(config.payload.aud).toBe(SERVICE_TOKEN_AUDIENCE);
+ expect(config.payload.scope).toBe("client-country");
+ });
});
diff --git a/autogpt_platform/frontend/src/lib/auth/country-token.ts b/autogpt_platform/frontend/src/lib/auth/country-token.ts
new file mode 100644
index 0000000000..061ed6f0d3
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/country-token.ts
@@ -0,0 +1,24 @@
+import { mintServiceToken } from "./service-token";
+
+export const CLIENT_COUNTRY_SCOPE = "client-country";
+
+// Tokens live 60s; reusing one for 30s leaves every sent token 30s to spare
+// while minting at most once per country per half-minute per instance.
+const REUSE_MS = 30_000;
+
+const minted = new Map<string, { token: string; mintedAt: number }>();
+
+/**
+ * The visitor's country as a frontend service token the backend can verify.
+ * The backend is reachable directly, so a plain country header would be
+ * whatever the caller typed; a signed one can only come from here.
+ */
+export async function getCountryToken(country: string) {
+ const code = country.trim().toUpperCase();
+ if (!/^[A-Z]{2}$/.test(code)) return null;
+ const cached = minted.get(code);
+ if (cached && Date.now() - cached.mintedAt < REUSE_MS) return cached.token;
+ const token = await mintServiceToken(CLIENT_COUNTRY_SCOPE, { country: code });
+ minted.set(code, { token, mintedAt: Date.now() });
+ return token;
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/service-token.ts b/autogpt_platform/frontend/src/lib/auth/service-token.ts
index 4f3b2a0e6c..239970bcef 100644
--- a/autogpt_platform/frontend/src/lib/auth/service-token.ts
+++ b/autogpt_platform/frontend/src/lib/auth/service-token.ts
@@ -18,8 +18,13 @@ type SignJWTContext = Parameters<typeof signJWT>[0];
* emails). Signed with the same Better Auth JWKS key the backend already
* trusts for user tokens (JWT_JWKS_URL), but with a distinct audience and
* subject so user and service tokens can never stand in for each other.
+ * `claims` carries facts the frontend vouches for; it cannot override the
+ * subject, audience, scope or lifetime.
*/
-export async function mintServiceToken(scope: string) {
+export async function mintServiceToken(
+ scope: string,
+ claims: Record<string, string> = {},
+) {
// Dynamic import: auth.ts (via email.ts) imports this module, so a static
// import back to ./auth would create an init cycle.
const { auth } = await import("./auth");
@@ -38,6 +43,7 @@ export async function mintServiceToken(scope: string) {
jwks: { keyPairConfig: { alg: JWKS_ALG } },
},
payload: {
+ ...claims,
sub: FRONTEND_SERVICE_SUBJECT,
aud: SERVICE_TOKEN_AUDIENCE,
scope,
diff --git a/autogpt_platform/frontend/src/lib/constants.ts b/autogpt_platform/frontend/src/lib/constants.ts
index abf02032b6..2945dd0b3b 100644
--- a/autogpt_platform/frontend/src/lib/constants.ts
+++ b/autogpt_platform/frontend/src/lib/constants.ts
@@ -11,6 +11,8 @@ export const IMPERSONATION_COOKIE_NAME = "admin-impersonate-user-id";
// API key authentication
export const API_KEY_HEADER_NAME = "X-API-Key";
+export const CLIENT_COUNTRY_TOKEN_HEADER_NAME = "X-Client-Country-Token";
+export const VERCEL_COUNTRY_HEADER_NAME = "x-vercel-ip-country";
// Layout
export const NAVBAR_HEIGHT_PX = 60;