Skip to content

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

fix(platform): pre-check invite eligibility before Supabase signup (#12451)

Otto02708bcd0005
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 4d07d53c7f..ec501f7c64 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -24,7 +24,7 @@ from fastapi import (
UploadFile,
)
from fastapi.concurrency import run_in_threadpool
-from pydantic import BaseModel
+from pydantic import BaseModel, EmailStr
from starlette.status import HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND
from typing_extensions import Optional, TypedDict
@@ -55,7 +55,11 @@ from backend.data.credit import (
set_auto_top_up,
)
from backend.data.graph import GraphSettings
-from backend.data.invited_user import get_or_activate_user
+from backend.data.invited_user import (
+ check_invite_eligibility,
+ get_or_activate_user,
+ is_internal_email,
+)
from backend.data.model import CredentialsMetaInput, UserOnboarding
from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
from backend.data.onboarding import (
@@ -70,6 +74,7 @@ from backend.data.onboarding import (
reset_user_onboarding,
update_user_onboarding,
)
+from backend.data.redis_client import get_redis_async
from backend.data.user import (
get_user_by_id,
get_user_notification_preference,
@@ -129,6 +134,69 @@ v1_router = APIRouter()
_tally_background_tasks: set[asyncio.Task] = set()
+class CheckInviteRequest(BaseModel):
+ email: EmailStr
+
+
+class CheckInviteResponse(BaseModel):
+ allowed: bool
+
+
+_CHECK_INVITE_RATE_LIMIT = 10 # requests
+_CHECK_INVITE_RATE_WINDOW = 60 # seconds
+
+
+@v1_router.post(
+ "/auth/check-invite",
+ summary="Check if an email is allowed to sign up",
+ tags=["auth"],
+)
+async def check_invite_route(
+ http_request: Request,
+ request: CheckInviteRequest,
+) -> CheckInviteResponse:
+ """Check if an email is allowed to sign up (no auth required).
+
+ Called by the frontend before creating a Supabase auth user to prevent
+ orphaned accounts when the invite gate is enabled.
+ """
+ client_ip = (
+ http_request.headers.get("x-forwarded-for", "").split(",")[0].strip()
+ or http_request.headers.get("x-real-ip", "")
+ or (http_request.client.host if http_request.client else "unknown")
+ )
+ rate_key = f"rate:check-invite:{client_ip}"
+ try:
+ redis = await get_redis_async()
+ # Use a pipeline so that incr + expire are sent atomically.
+ # This prevents the key from persisting indefinitely when expire fails
+ # after a successful incr (which would permanently block the IP once
+ # the count exceeds the limit).
+ # NOTE: pipeline command methods (incr, expire) are NOT awaitable —
+ # they queue the command and return the pipeline. Only execute() is
+ # awaited, which flushes all queued commands in a single round-trip.
+ pipe = redis.pipeline()
+ pipe.incr(rate_key)
+ pipe.expire(rate_key, _CHECK_INVITE_RATE_WINDOW)
+ results = await pipe.execute()
+ count = results[0]
+ if count > _CHECK_INVITE_RATE_LIMIT:
+ raise HTTPException(status_code=429, detail="Too many requests")
+ except HTTPException:
+ raise
+ except Exception:
+ logger.debug("Rate limit check failed for check-invite, failing open")
+
+ if not settings.config.enable_invite_gate:
+ return CheckInviteResponse(allowed=True)
+
+ if is_internal_email(request.email):
+ return CheckInviteResponse(allowed=True)
+
+ allowed = await check_invite_eligibility(request.email)
+ return CheckInviteResponse(allowed=allowed)
+
+
@v1_router.post(
"/auth/user",
summary="Get or create user",
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index 7fb2a6037e..ec7867c555 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -35,6 +35,102 @@ def setup_app_auth(mock_jwt_user, setup_test_user):
app.dependency_overrides.clear()
+# check_invite_route tests
+
+_RATE_LIMIT_PATCH = "backend.api.features.v1.get_redis_async"
+
+
+def _make_redis_mock(count: int = 1) -> AsyncMock:
+ """Return a mock Redis client that reports `count` for the rate-limit key.
+
+ The route uses a pipeline where incr/expire are synchronous (they queue
+ commands and return the pipeline) and only execute() is awaited.
+ """
+ mock_pipe = Mock()
+ mock_pipe.incr = Mock(return_value=mock_pipe)
+ mock_pipe.expire = Mock(return_value=mock_pipe)
+ mock_pipe.execute = AsyncMock(return_value=[count, True])
+
+ mock_redis = AsyncMock()
+ mock_redis.pipeline = Mock(return_value=mock_pipe)
+ return mock_redis
+
+
+def test_check_invite_gate_disabled(mocker: pytest_mock.MockFixture) -> None:
+ """When enable_invite_gate is False every email is allowed."""
+ mocker.patch(_RATE_LIMIT_PATCH, return_value=_make_redis_mock())
+ mocker.patch(
+ "backend.api.features.v1.settings",
+ Mock(config=Mock(enable_invite_gate=False)),
+ )
+
+ response = client.post("/auth/check-invite", json={"email": "[email protected]"})
+
+ assert response.status_code == 200
+ assert response.json() == {"allowed": True}
+
+
+def test_check_invite_internal_email_bypasses_gate(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """@agpt.co addresses bypass the gate even when it is enabled."""
+ mocker.patch(_RATE_LIMIT_PATCH, return_value=_make_redis_mock())
+ mocker.patch(
+ "backend.api.features.v1.settings",
+ Mock(config=Mock(enable_invite_gate=True)),
+ )
+
+ response = client.post("/auth/check-invite", json={"email": "[email protected]"})
+
+ assert response.status_code == 200
+ assert response.json() == {"allowed": True}
+
+
+def test_check_invite_eligible_email(mocker: pytest_mock.MockFixture) -> None:
+ """An email with INVITED status is allowed when the gate is enabled."""
+ mocker.patch(_RATE_LIMIT_PATCH, return_value=_make_redis_mock())
+ mocker.patch(
+ "backend.api.features.v1.settings",
+ Mock(config=Mock(enable_invite_gate=True)),
+ )
+ mocker.patch(
+ "backend.api.features.v1.check_invite_eligibility",
+ new=AsyncMock(return_value=True),
+ )
+
+ response = client.post("/auth/check-invite", json={"email": "[email protected]"})
+
+ assert response.status_code == 200
+ assert response.json() == {"allowed": True}
+
+
+def test_check_invite_ineligible_email(mocker: pytest_mock.MockFixture) -> None:
+ """An email without an active invite is denied when the gate is enabled."""
+ mocker.patch(_RATE_LIMIT_PATCH, return_value=_make_redis_mock())
+ mocker.patch(
+ "backend.api.features.v1.settings",
+ Mock(config=Mock(enable_invite_gate=True)),
+ )
+ mocker.patch(
+ "backend.api.features.v1.check_invite_eligibility",
+ new=AsyncMock(return_value=False),
+ )
+
+ response = client.post("/auth/check-invite", json={"email": "[email protected]"})
+
+ assert response.status_code == 200
+ assert response.json() == {"allowed": False}
+
+
+def test_check_invite_rate_limit_exceeded(mocker: pytest_mock.MockFixture) -> None:
+ """Requests beyond the per-IP rate limit receive HTTP 429."""
+ mocker.patch(_RATE_LIMIT_PATCH, return_value=_make_redis_mock(count=11))
+
+ response = client.post("/auth/check-invite", json={"email": "[email protected]"})
+
+ assert response.status_code == 429
+
+
# Auth endpoints tests
def test_get_or_create_user_route(
mocker: pytest_mock.MockFixture,
diff --git a/autogpt_platform/backend/backend/data/invited_user.py b/autogpt_platform/backend/backend/data/invited_user.py
index 077b29bf69..74bd61e88c 100644
--- a/autogpt_platform/backend/backend/data/invited_user.py
+++ b/autogpt_platform/backend/backend/data/invited_user.py
@@ -110,6 +110,11 @@ def normalize_email(email: str) -> str:
return email.strip().lower()
+def is_internal_email(email: str) -> bool:
+ """Return True for @agpt.co addresses, which always bypass the invite gate."""
+ return normalize_email(email).endswith("@agpt.co")
+
+
def _normalize_name(name: Optional[str]) -> Optional[str]:
if name is None:
return None
@@ -210,6 +215,25 @@ async def _apply_tally_understanding(
)
+async def check_invite_eligibility(email: str) -> bool:
+ """Check if an email is allowed to sign up based on the invite list.
+
+ Args:
+ email: The email to check (will be normalized internally).
+
+ Returns True if the email has an active (INVITED) invite record.
+ Does NOT check enable_invite_gate — the caller is responsible for that.
+ """
+ email = normalize_email(email)
+ invited_user = await prisma.models.InvitedUser.prisma().find_unique(
+ where={"email": email}
+ )
+ return (
+ invited_user is not None
+ and invited_user.status == prisma.enums.InvitedUserStatus.INVITED
+ )
+
+
async def list_invited_users(
page: int = 1,
page_size: int = 50,
@@ -664,7 +688,7 @@ async def get_or_activate_user(user_data: dict) -> User:
if existing_user is not None:
return existing_user
- if not _settings.config.enable_invite_gate or normalized_email.endswith("@agpt.co"):
+ if not _settings.config.enable_invite_gate or is_internal_email(normalized_email):
return await _open_signup_create_user(
auth_user_id, normalized_email, metadata_name
)
diff --git a/autogpt_platform/backend/backend/data/invited_user_test.py b/autogpt_platform/backend/backend/data/invited_user_test.py
index 48e2d822b8..613c8de287 100644
--- a/autogpt_platform/backend/backend/data/invited_user_test.py
+++ b/autogpt_platform/backend/backend/data/invited_user_test.py
@@ -14,6 +14,7 @@ from backend.util.exceptions import NotAuthorizedError, PreconditionFailed
from .invited_user import (
InvitedUserRecord,
bulk_create_invited_users_from_file,
+ check_invite_eligibility,
create_invited_user,
get_or_activate_user,
retry_invited_user_tally,
@@ -247,6 +248,10 @@ async def test_get_or_activate_user_creates_user_from_invite(
"backend.data.invited_user._apply_tally_understanding",
AsyncMock(),
)
+ mocker.patch(
+ "backend.data.invited_user._settings.config.enable_invite_gate",
+ True,
+ )
mocker.patch("backend.data.invited_user.transaction", fake_transaction)
mocker.patch(
"backend.data.invited_user.prisma.models.User.prisma", side_effect=user_prisma
@@ -333,3 +338,72 @@ async def test_bulk_create_invited_users_handles_csv_duplicates_and_invalid_rows
"SKIPPED",
]
assert create_invited.await_count == 2
+
+
+# ---------------------------------------------------------------------------
+# check_invite_eligibility tests
+# ---------------------------------------------------------------------------
+
+
+async def test_check_invite_eligibility_returns_true_for_invited(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ invited = _invited_user_db_record(status=prisma.enums.InvitedUserStatus.INVITED)
+ repo = Mock()
+ repo.find_unique = AsyncMock(return_value=invited)
+ mocker.patch(
+ "backend.data.invited_user.prisma.models.InvitedUser.prisma",
+ return_value=repo,
+ )
+
+ result = await check_invite_eligibility("[email protected]")
+ assert result is True
+ repo.find_unique.assert_awaited_once()
+
+
+async def test_check_invite_eligibility_returns_false_for_no_record(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ repo = Mock()
+ repo.find_unique = AsyncMock(return_value=None)
+ mocker.patch(
+ "backend.data.invited_user.prisma.models.InvitedUser.prisma",
+ return_value=repo,
+ )
+
+ result = await check_invite_eligibility("[email protected]")
+ assert result is False
+
+
+async def test_check_invite_eligibility_returns_false_for_claimed(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ claimed = _invited_user_db_record(status=prisma.enums.InvitedUserStatus.CLAIMED)
+ repo = Mock()
+ repo.find_unique = AsyncMock(return_value=claimed)
+ mocker.patch(
+ "backend.data.invited_user.prisma.models.InvitedUser.prisma",
+ return_value=repo,
+ )
+
+ result = await check_invite_eligibility("[email protected]")
+ assert result is False
+
+
+async def test_check_invite_eligibility_returns_false_for_revoked(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ revoked = _invited_user_db_record(status=prisma.enums.InvitedUserStatus.REVOKED)
+ repo = Mock()
+ repo.find_unique = AsyncMock(return_value=revoked)
+ mocker.patch(
+ "backend.data.invited_user.prisma.models.InvitedUser.prisma",
+ return_value=repo,
+ )
+
+ result = await check_invite_eligibility("[email protected]")
+ assert result is False
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index de9021dc79..deb707f0dd 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -122,7 +122,7 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="If authentication is enabled or not",
)
enable_invite_gate: bool = Field(
- default=True,
+ default=False,
description="If the invite-only signup gate is enforced",
)
enable_credit: bool = Field(
diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts b/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts
index 13da18b77c..364dcd934c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts
@@ -1,7 +1,11 @@
"use server";
-import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/auth";
+import {
+ postV1CheckIfAnEmailIsAllowedToSignUp,
+ postV1GetOrCreateUser,
+} from "@/app/api/__generated__/endpoints/auth/auth";
import { getOnboardingStatus, resolveResponse } from "@/app/api/helpers";
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { signupFormSchema } from "@/types/auth";
import * as Sentry from "@sentry/nextjs";
@@ -28,6 +32,31 @@ export async function signup(
};
}
+ // Pre-check invite eligibility before creating a Supabase auth user.
+ // This prevents orphaned auth accounts when the invite gate is enabled.
+ try {
+ const checkResult = await resolveResponse(
+ postV1CheckIfAnEmailIsAllowedToSignUp({ email: parsed.data.email }),
+ );
+ if (!checkResult.allowed) {
+ return { success: false, error: "not_allowed" };
+ }
+ // If the check fails (non-OK or backend unreachable), fall through to
+ // signup — the backend-level check in get_or_activate_user() catches it.
+ } catch (precheckError) {
+ if (precheckError instanceof ApiError) {
+ Sentry.captureMessage(
+ `Invite pre-check returned HTTP ${precheckError.status}`,
+ { level: "warning", tags: { flow: "signup_precheck" } },
+ );
+ } else {
+ Sentry.captureException(precheckError, {
+ tags: { flow: "signup_precheck" },
+ });
+ }
+ // Graceful fallback: don't block signup if the pre-check itself fails.
+ }
+
const supabase = await getServerSupabase();
if (!supabase) {
return {
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 0d8055b91e..4ea81f596a 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -299,6 +299,40 @@
}
}
},
+ "/api/auth/check-invite": {
+ "post": {
+ "tags": ["v1", "auth"],
+ "summary": "Check if an email is allowed to sign up",
+ "description": "Check if an email is allowed to sign up (no auth required).\n\nCalled by the frontend before creating a Supabase auth user to prevent\norphaned accounts when the invite gate is enabled.",
+ "operationId": "postV1Check if an email is allowed to sign up",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/CheckInviteRequest" }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/CheckInviteResponse" }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/auth/user": {
"post": {
"tags": ["v1", "auth"],
@@ -8441,6 +8475,20 @@
"required": ["query", "conversation_history", "message_id"],
"title": "ChatRequest"
},
+ "CheckInviteRequest": {
+ "properties": {
+ "email": { "type": "string", "format": "email", "title": "Email" }
+ },
+ "type": "object",
+ "required": ["email"],
+ "title": "CheckInviteRequest"
+ },
+ "CheckInviteResponse": {
+ "properties": { "allowed": { "type": "boolean", "title": "Allowed" } },
+ "type": "object",
+ "required": ["allowed"],
+ "title": "CheckInviteResponse"
+ },
"ClarificationNeededResponse": {
"properties": {
"type": {