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): a banned account is refused by the API and its scheduled runs stop (#15701)

Reinier van der Leerf7bc61e898b6
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py
index 3d45a5fbd1..6038370b9c 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py
@@ -12,7 +12,7 @@ from collections import OrderedDict
import fastapi
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
-from .jwt_utils import get_jwt_payload, verify_user
+from .jwt_utils import get_jwt_payload, parse_jwt_token_async, verify_user
from .models import RequestContext, User
from .permissions import (
OrgAction,
@@ -26,6 +26,12 @@ optional_bearer = HTTPBearer(auto_error=False)
# Header name for admin impersonation
IMPERSONATION_HEADER_NAME = "X-Act-As-User-Id"
+# The frontend signs the user out on this code (`account-banned.ts`).
+ACCOUNT_BANNED_DETAIL = {
+ "code": "account_banned",
+ "message": "This account has been banned.",
+}
+
logger = logging.getLogger(__name__)
# Recently settled self-heals, id -> monotonic expiry: a confirmed row for the
@@ -104,7 +110,7 @@ async def _settle_heal(user_id: str, jwt_payload: dict) -> None:
)
-def get_optional_user_id(
+async def get_optional_user_id(
credentials: HTTPAuthorizationCredentials | None = fastapi.Security(
optional_bearer
),
@@ -120,23 +126,61 @@ def get_optional_user_id(
credentials: Optional HTTPAuthorizationCredentials object from FastAPI Security dependency.
Returns:
- The user ID (str) extracted from the JWT "sub" claim, or None if no valid token is present.
+ The user ID (str) extracted from the JWT "sub" claim, or None if no valid token is present
+ or its account is banned.
"""
if not credentials:
return None
try:
- # Parse JWT token to get user ID
- from autogpt_libs.auth.jwt_utils import parse_jwt_token
-
- payload = parse_jwt_token(credentials.credentials)
- return payload.get("sub")
+ # Off the event loop: a JWKS cache miss is a blocking fetch.
+ payload = await parse_jwt_token_async(credentials.credentials)
except Exception as e:
logger.debug(f"Auth token validation failed (anonymous access): {e}")
return None
+ user_id = payload.get("sub")
+ if not user_id:
+ return None
+ # A banned account, or one whose ban can't be read, reads these routes as
+ # someone signed out would; they stay up either way.
+ try:
+ banned = await _is_banned(user_id)
+ except Exception:
+ logger.warning(f"Ban lookup failed for {user_id}; answering as anonymous")
+ return None
+ return None if banned else user_id
+
+
+async def get_unbanned_jwt_payload(
+ jwt_payload: dict = fastapi.Security(get_jwt_payload),
+) -> dict:
+ """``get_jwt_payload``, refused with 403 when the token's subject is banned.
+
+ The resolvers below all read it, and FastAPI resolves it once per request.
+ Under impersonation the subject is the admin, who may act as a banned user.
+ """
+ user_id = jwt_payload.get("sub")
+ if user_id and await _is_banned(user_id):
+ raise fastapi.HTTPException(status_code=403, detail=ACCOUNT_BANNED_DETAIL)
+ return jwt_payload
+
+async def _is_banned(user_id: str) -> bool:
+ """False without the backend package or a connected DB, as the self-heal is:
+ every process that serves these routes has both."""
+ try:
+ from backend.data import db # deferred -- only needed at runtime
+ from backend.data.user import is_user_banned # deferred
+ except ImportError:
+ return False
+ if not db.is_connected():
+ return False
+ return await is_user_banned(user_id)
-async def requires_user(jwt_payload: dict = fastapi.Security(get_jwt_payload)) -> User:
+
+async def requires_user(
+ jwt_payload: dict = fastapi.Security(get_unbanned_jwt_payload),
+) -> User:
"""
FastAPI dependency that requires a valid authenticated user.
@@ -147,7 +191,7 @@ async def requires_user(jwt_payload: dict = fastapi.Security(get_jwt_payload)) -
async def requires_admin_user(
- jwt_payload: dict = fastapi.Security(get_jwt_payload),
+ jwt_payload: dict = fastapi.Security(get_unbanned_jwt_payload),
) -> User:
"""
FastAPI dependency that requires a valid admin user.
@@ -159,7 +203,8 @@ async def requires_admin_user(
async def get_user_id(
- request: fastapi.Request, jwt_payload: dict = fastapi.Security(get_jwt_payload)
+ request: fastapi.Request,
+ jwt_payload: dict = fastapi.Security(get_unbanned_jwt_payload),
) -> str:
"""
FastAPI dependency that returns the ID of the authenticated user.
@@ -327,7 +372,7 @@ async def _finish_account_bootstrap(jwt_payload: dict) -> None:
async def get_request_context(
request: fastapi.Request,
- jwt_payload: dict = fastapi.Security(get_jwt_payload),
+ jwt_payload: dict = fastapi.Security(get_unbanned_jwt_payload),
) -> RequestContext:
"""
FastAPI dependency that resolves the full org/workspace context for a request.
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
index 5a8731f834..960443bb3d 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
@@ -1283,3 +1283,97 @@ class TestEnsurePlatformUserOutcome:
)
is False
)
+
+
+class TestBannedAccount:
+ """The ban states themselves are covered against the real lookup in the
+ backend's ``api/banned_account_test.py``."""
+
+ @staticmethod
+ def _client(mocker: MockerFixture, *, banned: bool) -> tuple[TestClient, AsyncMock]:
+ import sys
+ import types
+
+ from autogpt_libs.auth.jwt_utils import get_jwt_payload
+
+ db_mod = types.ModuleType("backend.data.db")
+ mocker.patch.object(
+ db_mod, "is_connected", Mock(return_value=True), create=True
+ )
+ # The self-heal reads ``prisma`` directly; keep it out of the way.
+ mocker.patch.object(db_mod, "prisma", Mock(), create=True)
+ db_mod.prisma.is_connected = Mock(return_value=False)
+ user_mod = types.ModuleType("backend.data.user")
+ is_user_banned = AsyncMock(return_value=banned)
+ mocker.patch.object(user_mod, "is_user_banned", is_user_banned, create=True)
+ backend_data = types.ModuleType("backend.data")
+ mocker.patch.object(backend_data, "db", db_mod, create=True)
+ mocker.patch.dict(
+ sys.modules,
+ {
+ "backend": types.ModuleType("backend"),
+ "backend.data": backend_data,
+ "backend.data.db": db_mod,
+ "backend.data.user": user_mod,
+ },
+ )
+
+ app = FastAPI()
+
+ @app.get("/me", dependencies=[Security(requires_user)])
+ def me(user_id: str = Security(get_user_id)):
+ return {"user_id": user_id}
+
+ app.dependency_overrides[get_jwt_payload] = lambda: {
+ "sub": "user-1",
+ "role": "user",
+ }
+ return TestClient(app), is_user_banned
+
+ def test_a_banned_subject_gets_the_banned_detail(self, mocker: MockerFixture):
+ client, _ = self._client(mocker, banned=True)
+
+ response = client.get("/me")
+
+ assert response.status_code == 403
+ assert response.json() == {
+ "detail": {
+ "code": "account_banned",
+ "message": "This account has been banned.",
+ }
+ }
+
+ def test_two_resolvers_on_one_route_check_once(self, mocker: MockerFixture):
+ client, is_user_banned = self._client(mocker, banned=False)
+
+ response = client.get("/me")
+
+ assert response.status_code == 200
+ is_user_banned.assert_awaited_once_with("user-1")
+
+
+async def test_optional_user_id_parses_the_token_off_the_event_loop(
+ mocker: MockerFixture,
+):
+ """A JWKS cache miss is a blocking fetch; on the loop it stalls every request."""
+ import threading
+
+ from fastapi.security import HTTPAuthorizationCredentials
+
+ from autogpt_libs.auth.dependencies import get_optional_user_id
+
+ parsed_on = []
+
+ def parse(token, audience="authenticated"):
+ parsed_on.append(threading.get_ident())
+ return {"sub": "user-1"}
+
+ mocker.patch("autogpt_libs.auth.jwt_utils.parse_jwt_token", side_effect=parse)
+
+ user_id = await get_optional_user_id(
+ HTTPAuthorizationCredentials(scheme="Bearer", credentials="t")
+ )
+
+ assert user_id == "user-1"
+ assert parsed_on and parsed_on[0] != threading.get_ident()
diff --git a/autogpt_platform/backend/backend/api/banned_account_test.py b/autogpt_platform/backend/backend/api/banned_account_test.py
new file mode 100644
index 0000000000..0a2dd29098
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/banned_account_test.py
@@ -0,0 +1,137 @@
+"""A banned account is refused on every route that resolves a user from a JWT."""
+
+import fastapi
+import pytest
+from autogpt_libs.auth import (
+ get_optional_user_id,
+ get_request_context,
+ get_user_id,
+ requires_admin_user,
+ requires_user,
+)
+from autogpt_libs.auth.dependencies import (
+ ACCOUNT_BANNED_DETAIL,
+ get_unbanned_jwt_payload,
+)
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
+from fastapi.dependencies.models import Dependant
+from fastapi.routing import APIRoute
+from fastapi.testclient import TestClient
+
+from backend.api.rest_api import app as rest_app
+
+
+ "state, status",
+ [("banned", 403), ("until_tomorrow", 403), ("lapsed", 200), ("unbanned", 200)],
+)
+def test_a_route_answers_by_the_tokens_ban_state(auth_row, state, status):
+ user_id = auth_row(state)
+
+ response = _client({"sub": user_id, "role": "user"}).get("/user-id")
+
+ assert response.status_code == status
+ if status == 403:
+ assert response.json() == {"detail": ACCOUNT_BANNED_DETAIL}
+ else:
+ assert response.json() == {"user_id": user_id}
+
+
[email protected]("path", ["/user-id", "/user", "/admin", "/context"])
+def test_every_user_resolver_refuses_a_banned_account(auth_row, path):
+ client = _client({"sub": auth_row("banned"), "role": "admin"})
+
+ response = client.get(path)
+
+ assert response.status_code == 403
+ assert response.json()["detail"]["code"] == "account_banned"
+
+
+def test_an_admin_can_still_act_as_a_banned_user(auth_row):
+ banned = auth_row("banned")
+ client = _client({"sub": auth_row("unbanned"), "role": "admin"})
+
+ response = client.get("/user-id", headers={"X-Act-As-User-Id": banned})
+
+ assert response.status_code == 200
+ assert response.json() == {"user_id": banned}
+
+
[email protected]("state", ["banned", "unbanned"])
+def test_an_optional_auth_route_sees_a_banned_account_as_signed_out(
+ mocker, auth_row, state
+):
+ user_id = auth_row(state)
+ mocker.patch(
+ "autogpt_libs.auth.jwt_utils.parse_jwt_token", return_value={"sub": user_id}
+ )
+
+ response = _client({}).get("/optional", headers={"Authorization": "Bearer t"})
+
+ assert response.json() == {"user_id": None if state == "banned" else user_id}
+
+
+def test_an_optional_auth_route_answers_when_the_ban_is_unreadable(mocker):
+ mocker.patch("backend.data.db.is_connected", return_value=True)
+ mocker.patch(
+ "backend.data.user.is_user_banned",
+ new=mocker.AsyncMock(side_effect=ConnectionError()),
+ )
+ mocker.patch(
+ "autogpt_libs.auth.jwt_utils.parse_jwt_token", return_value={"sub": "u1"}
+ )
+
+ response = _client({}).get("/optional", headers={"Authorization": "Bearer t"})
+
+ assert response.status_code == 200
+ assert response.json() == {"user_id": None}
+
+
+def test_every_route_that_reads_a_token_refuses_a_banned_account():
+ """A route that takes ``get_jwt_payload`` without one of the resolvers
+ above would let a banned account through."""
+ unguarded = [
+ f"{sorted(route.methods)} {route.path}"
+ for route in rest_app.routes
+ if isinstance(route, APIRoute)
+ and get_jwt_payload in (calls := _dependency_calls(route.dependant))
+ and get_unbanned_jwt_payload not in calls
+ ]
+
+ assert unguarded == []
+
+
+def _client(jwt_payload: dict) -> TestClient:
+ app = fastapi.FastAPI()
+
+ @app.get("/user-id")
+ async def by_user_id(user_id: str = fastapi.Security(get_user_id)):
+ return {"user_id": user_id}
+
+ @app.get("/user", dependencies=[fastapi.Security(requires_user)])
+ async def by_user():
+ return {}
+
+ @app.get("/admin", dependencies=[fastapi.Security(requires_admin_user)])
+ async def by_admin():
+ return {}
+
+ @app.get("/context", dependencies=[fastapi.Security(get_request_context)])
+ async def by_context():
+ return {}
+
+ @app.get("/optional")
+ async def by_optional(user_id=fastapi.Security(get_optional_user_id)):
+ return {"user_id": user_id}
+
+ app.dependency_overrides[get_jwt_payload] = lambda: jwt_payload
+ return TestClient(app)
+
+
+def _dependency_calls(dependant: Dependant) -> set:
+ calls, stack = set(), list(dependant.dependencies)
+ while stack:
+ sub = stack.pop()
+ calls.add(sub.call)
+ stack.extend(sub.dependencies)
+ return calls
diff --git a/autogpt_platform/backend/backend/api/conftest.py b/autogpt_platform/backend/backend/api/conftest.py
index 5febf63fb7..09711ab8d8 100644
--- a/autogpt_platform/backend/backend/api/conftest.py
+++ b/autogpt_platform/backend/backend/api/conftest.py
@@ -14,6 +14,7 @@ from pytest_snapshot.plugin import Snapshot
from backend.copilot import rate_limit
from backend.copilot.rate_limit import is_user_paywalled as _REAL_IS_USER_PAYWALLED
from backend.data.pro_activation import UsageActivationState
+from backend.data.user import is_user_banned as _REAL_IS_USER_BANNED
from backend.util.feature_flag import Flag
# Every module that imports the check by name.
@@ -23,6 +24,14 @@ _PAYWALL_CHECK_SITES = (
"backend.api.features.integrations.router.is_user_paywalled",
"backend.copilot.gate.workflow.is_user_paywalled",
)
+_BAN_CHECK_SITES = (
+ "backend.data.user.is_user_banned",
+ "backend.api.external.middleware.is_user_banned",
+ "backend.api.features.integrations.router.is_user_banned",
+ "backend.api.ws_api.is_user_banned",
+ "backend.data.auth.oauth.is_user_banned",
+ "backend.executor.utils.is_user_banned",
+)
@pytest.fixture
@@ -136,3 +145,71 @@ def paywalled_user(mocker, test_user_id):
)
mocker.patch.object(rate_limit, "is_feature_enabled", new=payments_on)
return test_user_id
+
+
[email protected](autouse=True)
+def _no_bans(mocker):
+ """No account is banned unless a test asks for ``real_ban_lookup``. Once a
+ session test has connected Prisma, the real lookup would query it from
+ TestClient's own event loop."""
+ ban_off = mocker.AsyncMock(return_value=False)
+ for site in _BAN_CHECK_SITES:
+ mocker.patch(site, new=ban_off)
+
+
+def real_ban_lookup(mocker):
+ """Undoes ``_no_bans``."""
+ for site in _BAN_CHECK_SITES:
+ mocker.patch(site, new=_REAL_IS_USER_BANNED)
+
+
+def auth_row(mocker, real_ban_lookup):
+ """Give a fresh user id an auth row in one ban state, read by the real
+ ``is_user_banned``: ``auth_row("banned" | "until_tomorrow" | "lapsed" |
+ "unbanned") -> user_id``."""
+ import uuid
+ from datetime import datetime, timedelta, timezone
+
+ from prisma.models import AuthUser
+
+ from backend.data import db
+ from backend.data import user as user_module
+
+ now = datetime.now(timezone.utc)
+ states = {
+ "banned": (True, None),
+ "until_tomorrow": (True, now + timedelta(days=1)),
+ "lapsed": (True, now - timedelta(minutes=1)),
+ "unbanned": (None, None),
+ }
+ rows: dict[str, AuthUser] = {}
+
+ async def find_unique(where):
+ return rows.get(where["id"])
+
+ # Connected, so the lookup reads the row here rather than over the RPC.
+ mocker.patch.object(db, "is_connected", return_value=True)
+ mocker.patch.object(user_module, "AuthUser").prisma.return_value.find_unique = (
+ find_unique
+ )
+
+ def make(state: str) -> str:
+ user_id = str(uuid.uuid4())
+ banned, ban_expires = states[state]
+ rows[user_id] = AuthUser(
+ id=user_id,
+ name="Test",
+ email=f"{user_id}@example.com",
+ emailVerified=True,
+ banned=banned,
+ banExpires=ban_expires,
+ createdAt=now,
+ updatedAt=now,
+ )
+ return user_id
+
+ yield make
+ for user_id in rows:
+ _REAL_IS_USER_BANNED.cache_delete(user_id)
diff --git a/autogpt_platform/backend/backend/api/external/middleware.py b/autogpt_platform/backend/backend/api/external/middleware.py
index 4e1460b346..24ee3a1b4d 100644
--- a/autogpt_platform/backend/backend/api/external/middleware.py
+++ b/autogpt_platform/backend/backend/api/external/middleware.py
@@ -1,3 +1,4 @@
+from autogpt_libs.auth.dependencies import ACCOUNT_BANNED_DETAIL
from fastapi import HTTPException, Security, status
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer
from prisma.enums import APIKeyPermission
@@ -10,6 +11,7 @@ from backend.data.auth.oauth import (
OAuthAccessTokenInfo,
validate_access_token,
)
+from backend.data.user import is_user_banned
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
bearer_auth = HTTPBearer(auto_error=False)
@@ -29,6 +31,7 @@ async def require_api_key(api_key: str | None = Security(api_key_header)) -> API
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key"
)
+ await _refuse_banned_owner(api_key_obj)
return api_key_obj
@@ -47,6 +50,7 @@ async def require_access_token(
except (InvalidClientError, InvalidTokenError) as e:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
+ await _refuse_banned_owner(token_info)
return token_info
@@ -68,6 +72,7 @@ async def require_auth(
if api_key is not None:
api_key_info = await validate_api_key(api_key)
if api_key_info:
+ await _refuse_banned_owner(api_key_info)
return api_key_info
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key"
@@ -77,9 +82,10 @@ async def require_auth(
if bearer is not None:
try:
token_info, _ = await validate_access_token(bearer.credentials)
- return token_info
except (InvalidClientError, InvalidTokenError) as e:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
+ await _refuse_banned_owner(token_info)
+ return token_info
# No credentials provided
raise HTTPException(
@@ -88,6 +94,13 @@ async def require_auth(
)
+async def _refuse_banned_owner(auth: APIAuthorizationInfo) -> None:
+ if await is_user_banned(auth.user_id):
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN, detail=ACCOUNT_BANNED_DETAIL
+ )
+
+
def require_permission(*permissions: APIKeyPermission):
"""
Dependency function for checking required permissions.
diff --git a/autogpt_platform/backend/backend/api/external/middleware_test.py b/autogpt_platform/backend/backend/api/external/middleware_test.py
new file mode 100644
index 0000000000..a79d3ce77b
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/external/middleware_test.py
@@ -0,0 +1,87 @@
+"""An API key or OAuth access token is refused when its owner is banned."""
+
+from datetime import datetime, timedelta, timezone
+
+import fastapi
+import pytest
+from fastapi.testclient import TestClient
+from prisma.enums import APIKeyPermission, APIKeyStatus
+
+from backend.api.external import middleware
+from backend.data.auth.api_key import APIKeyInfo
+from backend.data.auth.oauth import OAuthAccessTokenInfo
+
+_NOW = datetime.now(timezone.utc)
+
+
+ "state, status",
+ [("banned", 403), ("until_tomorrow", 403), ("lapsed", 200), ("unbanned", 200)],
+)
+ "path, headers",
+ [
+ ("/auth", {"X-API-Key": "key"}),
+ ("/auth", {"Authorization": "Bearer token"}),
+ ("/api-key", {"X-API-Key": "key"}),
+ ("/access-token", {"Authorization": "Bearer token"}),
+ ],
+)
+def test_a_credential_answers_by_its_owners_ban_state(
+ mocker, auth_row, state, status, path, headers
+):
+ user_id = auth_row(state)
+ mocker.patch.object(middleware, "validate_api_key", return_value=_key(user_id))
+ mocker.patch.object(
+ middleware, "validate_access_token", return_value=(_token(user_id), None)
+ )
+
+ response = _client().get(path, headers=headers)
+
+ assert response.status_code == status
+ if status == 403:
+ assert response.json()["detail"]["code"] == "account_banned"
+ else:
+ assert response.json() == {"user_id": user_id}
+
+
+def _client() -> TestClient:
+ app = fastapi.FastAPI()
+
+ @app.get("/auth")
+ async def by_auth(auth=fastapi.Security(middleware.require_auth)):
+ return {"user_id": auth.user_id}
+
+ @app.get("/api-key")
+ async def by_api_key(auth=fastapi.Security(middleware.require_api_key)):
+ return {"user_id": auth.user_id}
+
+ @app.get("/access-token")
+ async def by_access_token(auth=fastapi.Security(middleware.require_access_token)):
+ return {"user_id": auth.user_id}
+
+ return TestClient(app)
+
+
+def _key(user_id: str) -> APIKeyInfo:
+ return APIKeyInfo(
+ id="key-1",
+ name="Key",
+ head="agpt_",
+ tail="abcd",
+ status=APIKeyStatus.ACTIVE,
+ user_id=user_id,
+ scopes=[APIKeyPermission.EXECUTE_GRAPH],
+ created_at=_NOW,
+ )
+
+
+def _token(user_id: str) -> OAuthAccessTokenInfo:
+ return OAuthAccessTokenInfo(
+ id="token-1",
+ user_id=user_id,
+ scopes=[APIKeyPermission.EXECUTE_GRAPH],
+ created_at=_NOW,
+ expires_at=_NOW + timedelta(hours=1),
+ application_id="app-1",
+ )
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index 11128cbb26..f4ea249e1f 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -43,6 +43,7 @@ from backend.data.model import (
is_sdk_default,
)
from backend.data.onboarding import OnboardingStep, complete_onboarding_step
+from backend.data.user import is_user_banned
from backend.executor.utils import add_graph_execution
from backend.integrations.codex.access import (
enforce_codex_access_http,
@@ -1264,6 +1265,11 @@ async def webhook_ingress_generic(
detail="Invalid webhook signature",
)
+ # Acknowledged so the provider doesn't retry; nothing runs for a banned owner.
+ if await is_user_banned(user_id):
+ logger.info(f"Dropping webhook #{webhook_id} delivery: owner is banned")
+ return
+
payload, event_type = await webhook_manager.validate_payload(
webhook, request, credentials
)
diff --git a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py
index 599e7fbfbe..007ee1ab48 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py
@@ -807,3 +807,32 @@ def test_a_webhook_runs_only_for_an_owner_with_a_plan(paywalled: bool, request):
expected = 0 if paywalled else 1
assert publish.await_count == reward.await_count == run_node.await_count
assert run_node.await_count == expected
+
+
+def test_a_banned_owners_delivery_is_acknowledged_and_dropped():
+ """200, so the provider doesn't retry; nothing is published or run."""
+ from backend.api.features.integrations import router as ingress_router
+
+ webhook = _make_webhook(ProviderName.COMPASS, triggered_nodes=[MagicMock()])
+ publish, onboarding, node_trigger = AsyncMock(), AsyncMock(), AsyncMock()
+ with ExitStack() as stack:
+ for p in _patch_ingress(webhook) + [
+ patch.object(
+ ingress_router,
+ "get_webhook_manager",
+ return_value=_manager(ProviderName.COMPASS),
+ ),
+ patch.object(
+ ingress_router, "is_user_banned", AsyncMock(return_value=True)
+ ),
+ patch.object(ingress_router, "publish_webhook_event", publish),
+ patch.object(ingress_router, "complete_onboarding_step", onboarding),
+ patch.object(ingress_router, "_execute_webhook_node_trigger", node_trigger),
+ ]:
+ stack.enter_context(p)
+ resp = _post("compass")
+
+ assert resp.status_code == 200
+ publish.assert_not_awaited()
+ onboarding.assert_not_awaited()
+ node_trigger.assert_not_called()
diff --git a/autogpt_platform/backend/backend/api/features/oauth_test.py b/autogpt_platform/backend/backend/api/features/oauth_test.py
index 4a0268e529..c1aaeb8583 100644
--- a/autogpt_platform/backend/backend/api/features/oauth_test.py
+++ b/autogpt_platform/backend/backend/api/features/oauth_test.py
@@ -24,6 +24,7 @@ import pytest
import pytest_asyncio
from autogpt_libs.api_key.keysmith import APIKeySmith
from prisma.enums import APIKeyPermission
+from prisma.models import AuthUser as PrismaAuthUser
from prisma.models import OAuthAccessToken as PrismaOAuthAccessToken
from prisma.models import OAuthApplication as PrismaOAuthApplication
from prisma.models import OAuthAuthorizationCode as PrismaOAuthAuthorizationCode
@@ -31,6 +32,7 @@ from prisma.models import OAuthRefreshToken as PrismaOAuthRefreshToken
from prisma.models import User as PrismaUser
from backend.api.rest_api import app
+from backend.data.user import is_user_banned
keysmith = APIKeySmith()
@@ -922,6 +924,92 @@ async def test_refresh_token_creates_new_tokens(
assert new_db_access.revokedAt is None
[email protected](loop_scope="session")
+async def test_a_banned_owners_tokens_neither_refresh_nor_introspect_active(
+ client: httpx.AsyncClient,
+ test_user: str,
+ test_oauth_app: dict,
+ real_ban_lookup,
+):
+ """The external API refuses them anyway; the app hears it here too, and
+ the refresh token survives for when the ban is lifted."""
+ from urllib.parse import parse_qs, urlparse
+
+ verifier, challenge = generate_pkce()
+ auth_response = await client.post(
+ "/api/oauth/authorize",
+ json={
+ "client_id": test_oauth_app["client_id"],
+ "redirect_uri": test_oauth_app["redirect_uri"],
+ "scopes": ["EXECUTE_GRAPH"],
+ "state": "banned_test",
+ "response_type": "code",
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ },
+ follow_redirects=False,
+ )
+ auth_code = parse_qs(urlparse(auth_response.json()["redirect_url"]).query)["code"][
+ 0
+ ]
+ tokens = (
+ await client.post(
+ "/api/oauth/token",
+ json={
+ "grant_type": "authorization_code",
+ "code": auth_code,
+ "redirect_uri": test_oauth_app["redirect_uri"],
+ "client_id": test_oauth_app["client_id"],
+ "client_secret": test_oauth_app["client_secret"],
+ "code_verifier": verifier,
+ },
+ )
+ ).json()
+ app_credentials = {
+ "client_id": test_oauth_app["client_id"],
+ "client_secret": test_oauth_app["client_secret"],
+ }
+
+ await PrismaAuthUser.prisma().create(
+ data={
+ "id": test_user,
+ "name": "Banned",
+ "email": f"banned-{test_user}@example.com",
+ "banned": True,
+ }
+ )
+ is_user_banned.cache_delete(test_user)
+ try:
+ refresh = await client.post(
+ "/api/oauth/token",
+ json={
+ "grant_type": "refresh_token",
+ "refresh_token": tokens["refresh_token"],
+ **app_credentials,
+ },
+ )
+ introspected = [
+ (
+ await client.post(
+ "/api/oauth/introspect",
+ json={"token": tokens[kind], **app_credentials},
+ )
+ ).json()
+ for kind in ("access_token", "refresh_token")
+ ]
+ finally:
+ await PrismaAuthUser.prisma().delete(where={"id": test_user})
+ is_user_banned.cache_delete(test_user)
+
+ assert refresh.status_code == 400
+ assert [result["active"] for result in introspected] == [False, False]
+ refresh_hash = hashlib.sha256(tokens["refresh_token"].encode()).hexdigest()
+ stored = await PrismaOAuthRefreshToken.prisma().find_unique(
+ where={"token": refresh_hash}
+ )
+ assert stored is not None and stored.revokedAt is None
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_token_refresh_invalid_token(
client: httpx.AsyncClient,
diff --git a/autogpt_platform/backend/backend/api/ws_api.py b/autogpt_platform/backend/backend/api/ws_api.py
index 2eb5cf3e11..458e20b9c8 100644
--- a/autogpt_platform/backend/backend/api/ws_api.py
+++ b/autogpt_platform/backend/backend/api/ws_api.py
@@ -17,7 +17,7 @@ from backend.api.model import (
)
from backend.api.utils.cors import build_cors_params
from backend.data import db, redis_client
-from backend.data.user import DEFAULT_USER_ID
+from backend.data.user import DEFAULT_USER_ID, is_user_banned
from backend.monitoring.instrumentation import (
instrument_fastapi,
update_websocket_connections,
@@ -28,6 +28,8 @@ from backend.util.settings import AppEnvironment, Config, Settings
logger = logging.getLogger(__name__)
settings = Settings()
+ACCOUNT_BANNED_CLOSE_CODE = 4004
+
@asynccontextmanager
async def lifespan(app: FastAPI):
@@ -83,14 +85,26 @@ async def authenticate_websocket(websocket: WebSocket) -> str:
try:
payload = await parse_jwt_token_async(token)
- user_id = payload.get("sub")
- if not user_id:
- await websocket.close(code=4002, reason="Invalid token")
- return ""
- return user_id
except ValueError:
await websocket.close(code=4003, reason="Invalid token")
return ""
+ user_id = payload.get("sub")
+ if not user_id:
+ await websocket.close(code=4002, reason="Invalid token")
+ return ""
+
+ # Refused when the ban can't be read, as a request to a signed-in route is;
+ # 1011 rather than the ban's code, so an outage never reads as a ban.
+ try:
+ banned = await is_user_banned(user_id)
+ except Exception:
+ logger.warning(f"Ban lookup failed for user #{user_id}; refusing the socket")
+ await websocket.close(code=1011, reason="Try again")
+ return ""
+ if banned:
+ await websocket.close(code=ACCOUNT_BANNED_CLOSE_CODE, reason="Banned")
+ return ""
+ return user_id
# ===================== Message Handlers ===================== #
@@ -242,6 +256,10 @@ async def websocket_router(
try:
while True:
data = await websocket.receive_text()
+ # The socket outlives its token, so a ban ends it at the next message.
+ if await _banned_now(user_id):
+ await websocket.close(code=ACCOUNT_BANNED_CLOSE_CODE, reason="Banned")
+ break
try:
message = WSMessage.model_validate_json(data)
except pydantic.ValidationError as e:
@@ -332,6 +350,15 @@ async def websocket_router(
update_websocket_connections(user_id, -1)
+async def _banned_now(user_id: str) -> bool:
+ """A lookup that fails keeps the socket; the next message asks again."""
+ try:
+ return await is_user_banned(user_id)
+ except Exception:
+ logger.warning(f"Ban lookup failed for user #{user_id}; keeping the socket")
+ return False
+
+
@app.get("/")
@app.get("/health")
async def health():
diff --git a/autogpt_platform/backend/backend/api/ws_api_test.py b/autogpt_platform/backend/backend/api/ws_api_test.py
index b1d42da455..c8f7f8966f 100644
--- a/autogpt_platform/backend/backend/api/ws_api_test.py
+++ b/autogpt_platform/backend/backend/api/ws_api_test.py
@@ -434,6 +434,111 @@ async def test_authenticate_websocket_happy_path_returns_sub(mocker) -> None:
assert user_id == "user-X"
+async def test_authenticate_websocket_refuses_a_banned_account(mocker) -> None:
+ from backend.api.ws_api import authenticate_websocket
+
+ mocker.patch.object(settings.config, "enable_auth", True)
+ mocker.patch(
+ "backend.api.ws_api.parse_jwt_token_async",
+ new=AsyncMock(return_value={"sub": "user-X"}),
+ )
+ mocker.patch("backend.api.ws_api.is_user_banned", new=AsyncMock(return_value=True))
+ ws = AsyncMock(spec=WebSocket)
+ ws.query_params = {"token": "abc"}
+
+ user_id = await authenticate_websocket(ws)
+
+ ws.close.assert_awaited_once()
+ assert ws.close.call_args.kwargs["code"] == 4004
+ assert user_id == ""
+
+
+async def test_authenticate_websocket_refuses_when_the_ban_is_unreadable(
+ mocker,
+) -> None:
+ """A new socket fails closed, as a signed-in HTTP route does, and is not
+ told it is banned."""
+ from backend.api.ws_api import authenticate_websocket
+
+ mocker.patch.object(settings.config, "enable_auth", True)
+ mocker.patch(
+ "backend.api.ws_api.parse_jwt_token_async",
+ new=AsyncMock(return_value={"sub": "user-X"}),
+ )
+ mocker.patch(
+ "backend.api.ws_api.is_user_banned",
+ new=AsyncMock(side_effect=ConnectionError()),
+ )
+ ws = AsyncMock(spec=WebSocket)
+ ws.query_params = {"token": "abc"}
+
+ user_id = await authenticate_websocket(ws)
+
+ ws.close.assert_awaited_once()
+ assert ws.close.call_args.kwargs["code"] == 1011
+ assert user_id == ""
+
+
+async def test_a_ban_ends_an_open_socket_at_its_next_message(
+ mock_websocket: AsyncMock, mock_manager: AsyncMock, mocker
+) -> None:
+ """The token was checked when the socket opened; a ban set since then
+ closes it instead of handling the message."""
+ mocker.patch(
+ "backend.api.ws_api.authenticate_websocket", return_value=DEFAULT_USER_ID
+ )
+ mocker.patch("backend.api.ws_api.is_user_banned", new=AsyncMock(return_value=True))
+ mock_websocket.receive_text.side_effect = [
+ WSMessage(
+ method=WSMethod.SUBSCRIBE_GRAPH_EXEC,
+ data={"graph_exec_id": "test-graph-exec-1"},
+ ).model_dump_json(),
+ ]
+
+ await websocket_router(
+ cast(WebSocket, mock_websocket), cast(ConnectionManager, mock_manager)
+ )
+
+ assert mock_websocket.close.call_args.kwargs["code"] == 4004
+ mock_manager.subscribe_graph_exec.assert_not_called()
+ mock_manager.disconnect_socket.assert_called_once_with(
+ mock_websocket, user_id=DEFAULT_USER_ID
+ )
+
+
+async def test_an_unreadable_ban_keeps_an_open_socket(
+ mock_websocket: AsyncMock, mock_manager: AsyncMock, mocker
+) -> None:
+ mocker.patch(
+ "backend.api.ws_api.authenticate_websocket", return_value=DEFAULT_USER_ID
+ )
+ mocker.patch(
+ "backend.api.ws_api.is_user_banned",
+ new=AsyncMock(side_effect=ConnectionError()),
+ )
+ mock_websocket.receive_text.side_effect = [
+ WSMessage(
+ method=WSMethod.SUBSCRIBE_GRAPH_EXEC,
+ data={"graph_exec_id": "test-graph-exec-1"},
+ ).model_dump_json(),
+ WebSocketDisconnect(),
+ ]
+ mock_manager.subscribe_graph_exec.return_value = (
+ f"{DEFAULT_USER_ID}|graph_exec#test-graph-exec-1"
+ )
+
+ await websocket_router(
+ cast(WebSocket, mock_websocket), cast(ConnectionManager, mock_manager)
+ )
+
+ mock_websocket.close.assert_not_called()
+ mock_manager.subscribe_graph_exec.assert_called_once()
+
+
@pytest.mark.asyncio
async def test_authenticate_websocket_auth_disabled_returns_default(mocker) -> None:
from backend.api.ws_api import authenticate_websocket
diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.py
index a934717748..7c802bfe6c 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/generate.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py
@@ -21,6 +21,7 @@ from backend.data.db_accessors import (
user_db,
)
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
+from backend.data.user import is_user_banned
from backend.util.clients import get_database_manager_async_client
from backend.util.feature_flag import Flag, evaluate_feature_flag, is_feature_enabled
from backend.util.funnel_analytics import emit_funnel_event
@@ -275,6 +276,8 @@ async def generate_and_deliver_briefing(user_id: str) -> BriefingResult:
return {"status": "skipped", "reason": "flag_unavailable"}
return {"status": "skipped", "reason": "flag_disabled"}
+ if await is_user_banned(user_id):
+ return {"status": "skipped", "reason": "banned"}
if await is_user_paywalled(user_id):
return {"status": "skipped", "reason": "paywalled"}
diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
index 6d7732cb4c..9425ba6b85 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
@@ -324,6 +324,26 @@ def funnel(monkeypatch):
return mock
+async def test_generate_skips_a_banned_owner_before_any_work(monkeypatch):
+ from unittest.mock import AsyncMock, MagicMock
+
+ from backend.copilot.briefing import generate
+
+ monkeypatch.setattr(
+ generate, "evaluate_feature_flag", AsyncMock(return_value=(True, True))
+ )
+ monkeypatch.setattr(generate, "is_user_banned", AsyncMock(return_value=True))
+ get_user = AsyncMock()
+ monkeypatch.setattr(generate, "user_db", lambda: MagicMock(get_user_by_id=get_user))
+
+ result = await generate.generate_and_deliver_briefing("user-1")
+
+ # Not "flag_disabled": the cron stays registered for if the ban is lifted.
+ assert result == {"status": "skipped", "reason": "banned"}
+ get_user.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_generate_skips_when_already_delivered(monkeypatch):
from unittest.mock import AsyncMock, MagicMock
diff --git a/autogpt_platform/backend/backend/copilot/conftest.py b/autogpt_platform/backend/backend/copilot/conftest.py
new file mode 100644
index 0000000000..4de9a50363
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/conftest.py
@@ -0,0 +1,17 @@
+"""Fixtures shared by every copilot test."""
+
+import pytest
+
+
[email protected](autouse=True)
+def _no_bans(mocker):
+ """No owner is banned unless a test says so. Without this the lookup goes
+ to a DatabaseManager these tests don't run, and waits out its retries."""
+ for module in (
+ "backend.copilot.turn_queue",
+ "backend.copilot.executor.processor",
+ "backend.copilot.briefing.generate",
+ ):
+ mocker.patch(
+ f"{module}.is_user_banned", new=mocker.AsyncMock(return_value=False)
+ )
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.py
index 482e685cf8..19080682c3 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py
@@ -15,6 +15,8 @@ import uuid
from contextlib import AsyncExitStack
from typing import TYPE_CHECKING, Callable, cast
+from autogpt_libs.auth.dependencies import ACCOUNT_BANNED_DETAIL
+
from backend.copilot import stream_registry
from backend.copilot.baseline import stream_chat_completion_baseline
from backend.copilot.budget_gate import record_refusal, refusal_for
@@ -49,6 +51,7 @@ from backend.copilot.trial_cost_context import trial_cost_context
from backend.copilot.turn_pause import TurnPause
from backend.copilot.turn_tracing import TurnTrace, turn_transaction
from backend.data.model import OAuth2Credentials
+from backend.data.user import is_user_banned
from backend.executor.cluster_lock import ClusterLock
from backend.integrations.codex.transport import CodexCredentialIntegrityError
from backend.integrations.creds_manager import IntegrationCredentialsManager
@@ -621,6 +624,15 @@ class CoPilotProcessor:
try:
from backend.copilot.model import get_chat_session
+ # Every copilot turn starts here, whatever queued it.
+ if entry.user_id and await is_user_banned(entry.user_id):
+ log.info("Turn not started: the account is banned")
+ error_msg = ACCOUNT_BANNED_DETAIL["message"]
+ error_code = ACCOUNT_BANNED_DETAIL["code"]
+ # A refused account is not a failed schedule worth alerting on.
+ scheduled_watch = None
+ return
+
# Executor picked the turn up — replace the route's "Message
# received…" status while feature-flag resolution and service
# setup run.
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor_test.py b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
index 5dd7017352..9eb653bbfc 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor_test.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
@@ -27,7 +27,11 @@ from backend.copilot.executor.processor import (
_wait_for_expert_setup,
sync_fail_close_session,
)
-from backend.copilot.executor.utils import CoPilotExecutionEntry, CoPilotLogMetadata
+from backend.copilot.executor.utils import (
+ CoPilotExecutionEntry,
+ CoPilotLogMetadata,
+ ScheduledTurnOrigin,
+)
from backend.copilot.expert_context import (
EXPERT_SESSION_MISSING_MESSAGE,
EXPERT_SESSION_TEMPORARY_MESSAGE,
@@ -787,6 +791,44 @@ async def test_autopilot_session_skips_expert_tenancy_normalization() -> None:
assert stream_fn.call_args.kwargs["team_id"] == "entry-team"
+async def test_a_banned_owners_turn_ends_before_anything_runs() -> None:
+ """Every copilot turn reaches the executor, whatever queued it: schedules,
+ the AutoPilot block, approval wakes, sub-sessions and chat bots."""
+ entry = _make_entry().model_copy(
+ update={"scheduled": ScheduledTurnOrigin(schedule_id="sched-1")}
+ )
+ get_session = AsyncMock()
+ mark_completed = AsyncMock()
+
+ with (
+ patch(
+ "backend.copilot.executor.processor.is_user_banned",
+ new=AsyncMock(return_value=True),
+ ),
+ patch("backend.copilot.model.get_chat_session", new=get_session),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.mark_session_completed",
+ new=mark_completed,
+ ),
+ patch(
+ "backend.copilot.executor.scheduled_turn_alert.sentry_sdk.capture_message"
+ ) as alert,
+ ):
+ await CoPilotProcessor()._execute_async(
+ entry, threading.Event(), MagicMock(), _make_log()
+ )
+
+ get_session.assert_not_awaited()
+ mark_completed.assert_awaited_once_with(
+ "sess-1",
+ error_message="This account has been banned.",
+ error_code="account_banned",
+ turn_id="turn-1",
+ )
+ alert.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_unowned_expert_session_fails_before_engine_work() -> None:
session = ChatSession.new(
diff --git a/autogpt_platform/backend/backend/copilot/turn_queue.py b/autogpt_platform/backend/backend/copilot/turn_queue.py
index 3ca71849bd..d501f71106 100644
--- a/autogpt_platform/backend/backend/copilot/turn_queue.py
+++ b/autogpt_platform/backend/backend/copilot/turn_queue.py
@@ -73,6 +73,7 @@ from backend.copilot.trial_cost_context import (
restore_cost_context,
)
from backend.data.db_accessors import chat_db
+from backend.data.user import is_user_banned
from backend.integrations.codex.access import has_codex_access
logger = logging.getLogger(__name__)
@@ -807,10 +808,13 @@ async def turn_refusal(
) -> TurnRefusal | None:
"""Why a turn billed to this route may not start for this user, if so.
- Access first (Codex entitlement, the platform paywall), then the platform
- route's usage: its daily and weekly windows and a trial's total budget.
- Lookup errors propagate, so each caller decides what an unknown means.
+ A ban first, on every route; then access (Codex entitlement, the platform
+ paywall), then the platform route's usage: its daily and weekly windows and
+ a trial's total budget. Lookup errors propagate, so each caller decides what
+ an unknown means.
"""
+ if await is_user_banned(user_id):
+ return TurnRefusal(reason="is banned")
if llm_auth_provider == "codex":
if await has_codex_access(user_id):
return None
diff --git a/autogpt_platform/backend/backend/copilot/turn_queue_test.py b/autogpt_platform/backend/backend/copilot/turn_queue_test.py
index 137b05527c..4382c05254 100644
--- a/autogpt_platform/backend/backend/copilot/turn_queue_test.py
+++ b/autogpt_platform/backend/backend/copilot/turn_queue_test.py
@@ -1001,6 +1001,23 @@ async def test_dispatch_leaves_queued_when_user_paywalled() -> None:
db.update_chat_session_status.assert_not_awaited()
[email protected]("route", ["platform", "codex", "microsoft_365_copilot"])
+async def test_a_banned_owner_is_refused_on_every_route(route) -> None:
+ """The scheduler and the queue both ask here, and a ban outranks the
+ route: a ChatGPT or Microsoft 365 turn costs us nothing but still runs."""
+ with (
+ patch.object(turn_queue, "is_user_banned", new=AsyncMock(return_value=True)),
+ patch.object(turn_queue, "has_codex_access", new=AsyncMock(return_value=True)),
+ patch.object(
+ turn_queue, "is_user_paywalled", new=AsyncMock(return_value=False)
+ ),
+ ):
+ refusal = await turn_queue.turn_refusal("u1", route)
+
+ assert refusal == turn_queue.TurnRefusal(reason="is banned")
+
+
@pytest.mark.asyncio
async def test_codex_dispatch_skips_platform_billing_gates() -> None:
head = _queued_row()
diff --git a/autogpt_platform/backend/backend/data/auth/oauth.py b/autogpt_platform/backend/backend/data/auth/oauth.py
index e49586194c..631b6da0ef 100644
--- a/autogpt_platform/backend/backend/data/auth/oauth.py
+++ b/autogpt_platform/backend/backend/data/auth/oauth.py
@@ -25,6 +25,8 @@ from prisma.models import OAuthRefreshToken as PrismaOAuthRefreshToken
from prisma.types import OAuthApplicationUpdateInput
from pydantic import BaseModel, Field, SecretStr
+from backend.data.user import is_user_banned
+
from .base import APIAuthorizationInfo
logger = logging.getLogger(__name__)
@@ -652,6 +654,10 @@ async def refresh_tokens(
if rt.expiresAt < now:
raise InvalidGrantError("refresh token expired")
+ # Before the revoke, so the app's grant still works once a ban is lifted.
+ if await is_user_banned(rt.userId):
+ raise InvalidGrantError("the account this token belongs to is banned")
+
# Revoke old refresh token
await PrismaOAuthRefreshToken.prisma().update(
where={"token": token_hash},
@@ -739,6 +745,8 @@ async def introspect_token(
if token_type_hint != "refresh_token":
try:
token_info, app = await validate_access_token(token)
+ if await is_user_banned(token_info.user_id):
+ return TokenIntrospectionResult(active=False)
return TokenIntrospectionResult(
active=True,
scopes=list(s.value for s in token_info.scopes),
@@ -759,7 +767,9 @@ async def introspect_token(
if refresh_token and refresh_token.revokedAt is None:
# Check if valid (not expired)
now = datetime.now(timezone.utc)
- if refresh_token.expiresAt > now:
+ if refresh_token.expiresAt > now and not await is_user_banned(
+ refresh_token.userId
+ ):
app = await get_oauth_application_by_id(refresh_token.applicationId)
return TokenIntrospectionResult(
active=True,
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 19e071e849..245e9edb11 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -201,6 +201,7 @@ from backend.data.user import (
get_user_notification_preference,
get_user_subscription_tier,
heal_orphaned_auth_identities,
+ is_auth_user_banned,
is_marketing_opted_out,
release_welcome_email,
set_last_briefing_at,
@@ -412,6 +413,8 @@ class DatabaseManager(AppService):
# Exposed so Prisma-less workers (scheduler, copilot-executor) can build a
# full LaunchDarkly context — see backend/util/feature_flag.py.
get_auth_user_flag_fields = _(get_auth_user_flag_fields)
+ # Background work skips a banned owner in Prisma-less workers too.
+ is_auth_user_banned = _(is_auth_user_banned)
# Exposed for the scheduler's auth-identity invariant monitor.
heal_orphaned_auth_identities = _(heal_orphaned_auth_identities)
get_user_integrations = _(get_user_integrations)
@@ -931,6 +934,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
sync_subscription_from_stripe = d.sync_subscription_from_stripe
record_subscription_trial_cost = d.record_subscription_trial_cost
get_auth_user_flag_fields = d.get_auth_user_flag_fields
+ is_auth_user_banned = d.is_auth_user_banned
heal_orphaned_auth_identities = d.heal_orphaned_auth_identities
get_user_integrations = d.get_user_integrations
update_user_integrations = d.update_user_integrations
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index 17cef61931..c2f9de6b66 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -19,6 +19,7 @@ from prisma.types import JsonFilter, UserCreateInput, UserUpdateInput, UserWhere
from pydantic import BaseModel, ConfigDict
from backend.data.db import prisma, query_raw_with_schema, transaction
+from backend.data.db_accessors import user_db
from backend.data.model import (
CREDENTIALS_ADAPTER,
Credentials,
@@ -244,6 +245,25 @@ async def get_auth_user_flag_fields(user_id: str) -> Optional[AuthUserFlagFields
)
+@cached(maxsize=1000, ttl_seconds=30, shared_cache=True)
+async def is_user_banned(user_id: str) -> bool:
+ """Whether an admin ban (Better Auth's ``banned``/``banExpires``) holds now.
+
+ Works in any process; the cache is read before the DatabaseManager is.
+ Lookup errors propagate, and ``@cached`` stores no call that raised.
+ """
+ return await user_db().is_auth_user_banned(user_id)
+
+
+async def is_auth_user_banned(user_id: str) -> bool:
+ """The uncached read behind :func:`is_user_banned`. A lapsed temporary ban
+ and a missing auth row are not bans."""
+ user = await AuthUser.prisma().find_unique(where={"id": user_id})
+ if user is None or not user.banned:
+ return False
+ return user.banExpires is None or user.banExpires > datetime.now(timezone.utc)
+
+
class OrphanedAuthIdentity(BaseModel):
"""An auth identity (Better Auth user) with no platform ``User`` row."""
diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.py
index 4de3aae7d1..27288e44b6 100644
--- a/autogpt_platform/backend/backend/data/user_test.py
+++ b/autogpt_platform/backend/backend/data/user_test.py
@@ -2,9 +2,10 @@
import asyncio
import base64
+import uuid
from collections.abc import AsyncIterator, Iterator
from contextlib import asynccontextmanager
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from typing import Any
from unittest.mock import AsyncMock, MagicMock, call, patch
@@ -1691,6 +1692,35 @@ class TestGetAuthUserFlagFields:
assert fields is None
+class TestIsUserBanned:
+ """The ban states themselves are driven through the real dependencies in
+ ``api/banned_account_test.py``; these pin what those can't reach."""
+
+ @pytest.mark.asyncio
+ async def test_a_missing_auth_row_is_not_a_ban(self):
+ with patch.object(user_module, "AuthUser") as mock_auth_user:
+ mock_auth_user.prisma.return_value.find_unique = AsyncMock(
+ return_value=None
+ )
+ assert await user_module.is_auth_user_banned("no-auth-row") is False
+
+ @pytest.mark.asyncio
+ async def test_the_answer_is_shared_until_it_expires(self, mocker):
+ """Every request asks, so a hit must not reach the database."""
+ mocker.patch("backend.data.db.is_connected", return_value=True)
+ user_id = f"cached-{uuid.uuid4()}"
+ now = datetime.now(timezone.utc)
+ row = MagicMock(banned=True, banExpires=now + timedelta(days=1))
+ with patch.object(user_module, "AuthUser") as mock_auth_user:
+ find_unique = AsyncMock(return_value=row)
+ mock_auth_user.prisma.return_value.find_unique = find_unique
+ assert await user_module.is_user_banned(user_id) is True
+ assert await user_module.is_user_banned(user_id) is True
+ user_module.is_user_banned.cache_delete(user_id)
+
+ find_unique.assert_awaited_once_with(where={"id": user_id})
+
+
class TestGetUserDefaultChatRoute:
@pytest.mark.asyncio
async def test_returns_the_saved_route(self):
diff --git a/autogpt_platform/backend/backend/executor/conftest.py b/autogpt_platform/backend/backend/executor/conftest.py
index 943387c4c5..7593d04023 100644
--- a/autogpt_platform/backend/backend/executor/conftest.py
+++ b/autogpt_platform/backend/backend/executor/conftest.py
@@ -29,6 +29,20 @@ def _bypass_paywall(mocker):
)
[email protected](autouse=True)
+def _no_bans(mocker):
+ """No owner is banned unless a test says so. Without this the lookup goes
+ to a DatabaseManager these tests don't run, and waits out its retries."""
+ for module in (
+ "backend.executor.utils",
+ "backend.executor.scheduler",
+ "backend.copilot.turn_queue",
+ ):
+ mocker.patch(
+ f"{module}.is_user_banned", new=mocker.AsyncMock(return_value=False)
+ )
+
+
@pytest.fixture(autouse=True)
def _default_team_untenanted(mocker):
"""Default the born-tenanted fallback to a no-op for executor tests.
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 7d861b58a7..f4aacb61ef 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -96,6 +96,7 @@ from backend.data.memory_schedule import ScopeRunKind
from backend.data.model import CredentialsMetaInput, GraphInput
from backend.data.redis_client import get_redis_async
from backend.data.schedule import normalize_schedule_name
+from backend.data.user import is_user_banned
from backend.executor import schedule_events
from backend.executor import utils as execution_utils
from backend.executor.jobstore import WRITE_TIMEOUT, ResilientSQLAlchemyJobStore
@@ -126,6 +127,7 @@ from backend.util.exceptions import (
GraphValidationError,
NotAuthorizedError,
NotFoundError,
+ UserBannedError,
UserPaywalledError,
)
from backend.util.logging import PrefixFilter
@@ -348,6 +350,9 @@ async def _execute_graph(**kwargs):
# schedule stays registered so it resumes on its own once they
# subscribe, and a recurring tick is not an error worth paging on.
logger.info(f"Skipping scheduled run for graph #{args.graph_id}: {e}")
+ except UserBannedError as e:
+ # Kept registered, so the schedule resumes if the ban is lifted.
+ logger.info(f"Skipping scheduled run for graph #{args.graph_id}: {e}")
except ExpertPrivateTenancyNotFoundError:
# Graph schedules are recurring, so the next cron tick is the retry.
logger.warning(
@@ -1457,6 +1462,19 @@ def _memory_scope_may_fire(scope: MemoryScope) -> bool:
"""The registry gate of a dream-system cron (``memory_scope_may_fire``),
run on the scheduler loop. The gate bounds itself; if the bridge still
gives up, the gate's cancellation is requested and the run skipped."""
+ # A banned owner's crons stay registered and resume if the ban is lifted.
+ try:
+ banned = run_async(
+ is_user_banned(scope.owner_user_id),
+ timeout=bridge_timeout(),
+ cancel_on_timeout=True,
+ )
+ except Exception:
+ logger.warning(f"Memory cron of {scope_label(scope)} skipped: ban unreadable")
+ return False
+ if banned:
+ logger.info(f"Memory cron of {scope_label(scope)} skipped: owner is banned")
+ return False
try:
return run_async(
memory_scope_may_fire(scope, _expert_scope_status),
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index 7866364653..637cf1a5fc 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -6,6 +6,7 @@ backend test job (and counted by codecov), not just the integration suite.
"""
import asyncio
+import concurrent.futures
import logging
import threading
import time
@@ -56,6 +57,9 @@ from backend.executor.scheduler import (
_routine_turn_permissions,
_self_delete_copilot_turn_schedule,
_self_delete_morning_briefing_schedule,
+ execute_community_rebuild,
+ execute_nightly_batch_sync,
+ execute_skill_learning_sync,
reconcile_memory_scope_crons,
reconcile_stripe_tiers,
refresh_near_expiry_credentials,
@@ -63,6 +67,7 @@ from backend.executor.scheduler import (
from backend.util.exceptions import (
ExpertNotFoundError,
ExpertPrivateTenancyNotFoundError,
+ UserBannedError,
UserPaywalledError,
)
from backend.util.service import EXPOSED_FLAG
@@ -1287,7 +1292,14 @@ async def test_execute_graph_forwards_expert_id_and_schedule_id():
@pytest.mark.asyncio
-async def test_execute_graph_quietly_skips_paywalled_user(caplog):
+ "refusal",
+ [
+ UserPaywalledError("A subscription is required to run agents."),
+ UserBannedError("This account is banned, so its workflows can't run."),
+ ],
+)
+async def test_execute_graph_quietly_skips_a_refused_owner(caplog, refusal):
args = GraphExecutionJobArgs(
schedule_id="sched-1",
user_id="user-1",
@@ -1297,9 +1309,7 @@ async def test_execute_graph_quietly_skips_paywalled_user(caplog):
input_data={},
input_credentials={},
)
- mock_add = AsyncMock(
- side_effect=UserPaywalledError("A subscription is required to run agents.")
- )
+ mock_add = AsyncMock(side_effect=refusal)
mock_db = MagicMock()
mock_db.increment_onboarding_runs = AsyncMock()
@@ -1322,6 +1332,53 @@ async def test_execute_graph_quietly_skips_paywalled_user(caplog):
assert not any(record.levelno >= logging.ERROR for record in caplog.records)
+ "job, work",
+ [
+ (execute_community_rebuild, f"{_SCHEDULER_PATH}.rebuild_communities_for_user"),
+ (
+ execute_nightly_batch_sync,
+ "backend.copilot.dream.nightly_batch.run_nightly_batch_submit",
+ ),
+ (
+ execute_skill_learning_sync,
+ "backend.copilot.learning.nightly.run_skill_learning_pass",
+ ),
+ ],
+)
+def test_a_nightly_job_does_no_work_for_a_banned_owner(job, work):
+ def flag_on_and_owner_banned(coro, *args, **kwargs):
+ coro.close()
+ return True
+
+ with (
+ patch(f"{_SCHEDULER_PATH}.run_async", side_effect=flag_on_and_owner_banned),
+ patch(work) as work_fn,
+ ):
+ assert job("user-1") is None
+
+ work_fn.assert_not_called()
+
+
+def test_a_memory_cron_skips_when_the_ban_is_unreadable():
+ """Bounded by the registry gate's own budget, and skipped like it."""
+ timeouts = []
+
+ def ban_lookup_times_out(coro, *args, **kwargs):
+ coro.close()
+ timeouts.append(kwargs.get("timeout"))
+ raise concurrent.futures.TimeoutError()
+
+ with (
+ patch(f"{_SCHEDULER_PATH}.run_async", side_effect=ban_lookup_times_out),
+ patch("backend.copilot.dream.nightly_batch.run_nightly_batch_submit") as work,
+ ):
+ assert execute_nightly_batch_sync("user-1") is None
+
+ work.assert_not_called()
+ assert timeouts == [scheduler_module.bridge_timeout()]
+
+
@pytest.mark.asyncio
async def test_execute_graph_quietly_skips_unavailable_expert(caplog):
args = GraphExecutionJobArgs(
diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.py
index 33751f3aa4..9c4f5a26bf 100644
--- a/autogpt_platform/backend/backend/executor/utils.py
+++ b/autogpt_platform/backend/backend/executor/utils.py
@@ -48,6 +48,7 @@ from backend.data.model import (
NodeExecutionStats,
)
from backend.data.rabbitmq import Exchange, ExchangeType, Queue, RabbitMQConfig
+from backend.data.user import is_user_banned
from backend.integrations.credentials_store import is_system_credential
from backend.monitoring.instrumentation import record_graph_execution
from backend.util import product_analytics
@@ -63,6 +64,7 @@ from backend.util.exceptions import (
GraphNotFoundError,
GraphValidationError,
NotFoundError,
+ UserBannedError,
)
from backend.util.logging import TruncatedLogger, is_structured_logging_enabled
from backend.util.settings import Config
@@ -1318,7 +1320,7 @@ async def add_graph_execution(
graph_id=graph_id, status="validation_error", user_id=user_id
)
raise
- except UserPaywalledError:
+ except (UserPaywalledError, UserBannedError):
raise
except Exception:
record_graph_execution(graph_id=graph_id, status="error", user_id=user_id)
@@ -1409,6 +1411,8 @@ async def _add_graph_execution(
if not bypass_paywall and await is_user_paywalled(user_id):
raise UserPaywalledError("A subscription is required to run workflows.")
+ if await is_user_banned(user_id):
+ raise UserBannedError("This account is banned, so its workflows can't run.")
is_new_execution = graph_exec_id is None
context_expert_id = execution_context.expert_id if execution_context else None
diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.py
index 7304538ff2..682dd9edaa 100644
--- a/autogpt_platform/backend/backend/executor/utils_test.py
+++ b/autogpt_platform/backend/backend/executor/utils_test.py
@@ -2121,6 +2121,32 @@ async def test_add_graph_execution_bypass_paywall_skips_check(
paywall_mock.assert_not_called()
[email protected]("bypass_paywall", [False, True])
+async def test_add_graph_execution_refuses_a_banned_owner(
+ mocker: MockerFixture, bypass_paywall: bool
+):
+ """Every run starts here (schedules, webhooks, the external API, copilot
+ tools), and an admin requeue doesn't revive a banned account's run."""
+ from backend.util.exceptions import UserBannedError
+
+ mocker.patch(
+ "backend.executor.utils.is_user_banned",
+ new=mocker.AsyncMock(return_value=True),
+ )
+ mock_edb = mocker.patch("backend.executor.utils.execution_db")
+ mock_edb.create_graph_execution = mocker.AsyncMock()
+ mock_edb.get_graph_execution = mocker.AsyncMock()
+
+ with pytest.raises(UserBannedError):
+ await add_graph_execution(
+ graph_id="g", user_id="banned-user", bypass_paywall=bypass_paywall
+ )
+
+ mock_edb.create_graph_execution.assert_not_called()
+ mock_edb.get_graph_execution.assert_not_called()
+
+
# ============================================================================
# Born-tenanted fallback: a NEW execution created without an explicit org is
# tenanted at creation with the user's default org/team.
diff --git a/autogpt_platform/backend/backend/platform_linking/chat.py b/autogpt_platform/backend/backend/platform_linking/chat.py
index e579c07545..becb80acdf 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat.py
@@ -25,6 +25,7 @@ from backend.copilot.rate_limit import (
from backend.copilot.transports import resolve_default_chat_route
from backend.copilot.tree import root_envelope
from backend.data.db_accessors import orgs_db, platform_linking_db, workspace_db
+from backend.data.user import is_user_banned
from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
from backend.util.settings import Settings
from backend.util.workspace import WorkspaceManager
@@ -65,6 +66,21 @@ def _unavailable_denial() -> TurnDenial:
)
+async def _check_ban(user_id: str) -> TurnDenial | None:
+ """Fail closed on lookup failure, as the paywall check does."""
+ try:
+ banned = await is_user_banned(user_id)
+ except Exception:
+ logger.warning(
+ f"evaluate_turn_gate: ban lookup failed for ...{user_id[-8:]}",
+ exc_info=True,
+ )
+ return _unavailable_denial()
+ if not banned:
+ return None
+ return TurnDenial(reason="banned", message="This account has been banned.")
+
+
async def _check_paywall(user_id: str) -> TurnDenial | None:
"""Subscription paywall check — fail closed on lookup failure."""
try:
@@ -132,14 +148,18 @@ async def _check_usage_limits(user_id: str) -> TurnDenial | None:
async def evaluate_turn_gate(user_id: str) -> TurnDenial | None:
- """Apply the same subscription paywall + usage rate limits as the web UI.
+ """Apply the same ban, subscription paywall and usage limits as the web UI.
The bot enqueues turns directly into the executor, bypassing the
route-level paywall dependency and the dispatcher's rate-limit check, so
without this a NO_TIER / over-cap user would get unmetered free usage.
Returns a :class:`TurnDenial` to surface, or None when the turn may run.
"""
- return await _check_paywall(user_id) or await _check_usage_limits(user_id)
+ return (
+ await _check_ban(user_id)
+ or await _check_paywall(user_id)
+ or await _check_usage_limits(user_id)
+ )
async def resolve_owner(
diff --git a/autogpt_platform/backend/backend/platform_linking/chat_test.py b/autogpt_platform/backend/backend/platform_linking/chat_test.py
index 4e7b003e8b..a1d242d533 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat_test.py
@@ -780,6 +780,35 @@ class TestEnsureChatSession:
class TestEvaluateTurnGate:
_PATH = "backend.platform_linking.chat"
+ @pytest.fixture(autouse=True)
+ def _not_banned(self):
+ with patch(f"{self._PATH}.is_user_banned", AsyncMock(return_value=False)):
+ yield
+
+ @pytest.mark.asyncio
+ async def test_a_banned_owner_is_denied_before_the_paywall(self):
+ paywall = AsyncMock(return_value=True)
+ with (
+ patch(f"{self._PATH}.is_user_banned", AsyncMock(return_value=True)),
+ patch(f"{self._PATH}.is_user_paywalled", paywall),
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial == TurnDenial(
+ reason="banned", message="This account has been banned."
+ )
+ paywall.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_an_unreadable_ban_fails_closed(self):
+ with patch(
+ f"{self._PATH}.is_user_banned", AsyncMock(side_effect=ConnectionError())
+ ):
+ denial = await evaluate_turn_gate("user-1")
+
+ assert denial is not None
+ assert denial.reason == "unavailable"
+
@pytest.mark.asyncio
async def test_paywalled_returns_denial_with_button(self):
with (
diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.py
index d642bce30d..78ea746857 100644
--- a/autogpt_platform/backend/backend/platform_linking/models.py
+++ b/autogpt_platform/backend/backend/platform_linking/models.py
@@ -280,7 +280,7 @@ class TurnDenial(BaseModel):
directly into the executor.
"""
- reason: Literal["paywalled", "rate_limited", "unavailable"]
+ reason: Literal["banned", "paywalled", "rate_limited", "unavailable"]
message: str
button_label: str | None = None
button_url: str | None = None
diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.py
index 6f18f05d5e..9b2f50378a 100644
--- a/autogpt_platform/backend/backend/util/exceptions.py
+++ b/autogpt_platform/backend/backend/util/exceptions.py
@@ -144,6 +144,11 @@ class NotAuthorizedError(ValueError):
"""The user is not authorized to perform the requested operation"""
+class UserBannedError(NotAuthorizedError):
+ """The owner's account is banned. Raised where new work would start for it;
+ background callers skip the run."""
+
+
class GraphNotAccessibleError(NotAuthorizedError):
"""Raised when attempting to execute a graph that is not accessible to the user."""
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/banned-notice.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/banned-notice.test.tsx
new file mode 100644
index 0000000000..8600d64535
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/banned-notice.test.tsx
@@ -0,0 +1,34 @@
+import type { ReactNode } from "react";
+import { render, screen } from "@/tests/integrations/test-utils";
+import { describe, expect, test, vi } from "vitest";
+import LoginPage from "../page";
+
+let mockSearchParams = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: vi.fn(), push: vi.fn() }),
+ useSearchParams: () => mockSearchParams,
+ usePathname: () => "/login",
+}));
+
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ user: null, isUserLoading: false, isLoggedIn: false }),
+}));
+
+describe("LoginPage after a banned account is signed out", () => {
+ test("says why", () => {
+ mockSearchParams = new URLSearchParams({ account: "banned" });
+
+ render(<LoginPage />);
+
+ expect(
+ screen.getByText(
+ "This account has been banned. If you think this is a mistake, please contact support.",
+ ),
+ ).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts
index 6acd32f970..53bb196485 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts
@@ -1,5 +1,8 @@
import type { EmailVerificationNotice } from "@/lib/auth/email-verification";
+export const ACCOUNT_BANNED_NOTICE_COPY =
+ "This account has been banned. If you think this is a mistake, please contact support.";
+
export const EMAIL_VERIFICATION_NOTICE_COPY: Record<
EmailVerificationNotice,
string
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx
index 6fceef6f66..c725992a38 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx
@@ -16,7 +16,10 @@ import { environment } from "@/services/environment";
import { useSearchParams } from "next/navigation";
import { LoadingLogin } from "./components/LoadingLogin";
import { LoginMarketingPanel } from "./components/LoginMarketingPanel";
-import { EMAIL_VERIFICATION_NOTICE_COPY } from "./helpers";
+import {
+ ACCOUNT_BANNED_NOTICE_COPY,
+ EMAIL_VERIFICATION_NOTICE_COPY,
+} from "./helpers";
import { useLoginPage } from "./useLoginPage";
export const dynamic = "force-dynamic";
@@ -35,6 +38,7 @@ export default function LoginPage() {
nextUrl: safeNextUrl,
verificationEmail,
verificationNotice,
+ showBannedNotice,
isLoading,
isGoogleLoading,
isCloudEnv,
@@ -71,6 +75,12 @@ export default function LoginPage() {
</Text>
</div>
+ {showBannedNotice ? (
+ <Alert variant="error" className="mb-6">
+ <AlertDescription>{ACCOUNT_BANNED_NOTICE_COPY}</AlertDescription>
+ </Alert>
+ ) : null}
+
{verificationNotice ? (
<Alert className="mb-6">
<AlertDescription>
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts
index 013dccb644..8f234ced6d 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts
@@ -1,6 +1,7 @@
import { useToast } from "@/components/molecules/Toast/use-toast";
import { useCaptureMarketingPrompt } from "@/hooks/useCaptureMarketingPrompt";
import { sanitizeAuthNext } from "@/lib/auth-redirect";
+import { isBannedNotice } from "@/lib/auth/account-banned";
import {
EMAIL_VERIFICATION_NOTICE_PARAM,
getEmailVerificationNotice,
@@ -38,6 +39,7 @@ export function useLoginPage() {
const verificationNotice = getEmailVerificationNotice(
searchParams.get(EMAIL_VERIFICATION_NOTICE_PARAM),
);
+ const showBannedNotice = isBannedNotice(searchParams);
// Only honour explicit `?next=` deep links here. Generic "already logged in
// on /login, get me out" is handled by OnboardingProvider so the user lands
@@ -145,6 +147,7 @@ export function useLoginPage() {
nextUrl,
verificationEmail,
verificationNotice,
+ showBannedNotice,
user,
isLoading,
isGoogleLoading,
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/logout/__tests__/logout.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/logout/__tests__/logout.test.tsx
new file mode 100644
index 0000000000..8f9ebcff7c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/logout/__tests__/logout.test.tsx
@@ -0,0 +1,35 @@
+import { render, waitFor } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import LogoutPage from "../page";
+
+const mockReplace = vi.hoisted(() => vi.fn());
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: mockReplace, push: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+ usePathname: () => "/logout",
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ logOut: vi.fn().mockResolvedValue(undefined) }),
+}));
+
+describe("LogoutPage", () => {
+ afterEach(() => {
+ mockReplace.mockReset();
+ window.history.replaceState({}, "", "/");
+ });
+
+ test.each([
+ ["/logout?reason=banned", "/login?account=banned"],
+ ["/logout", "/login"],
+ ])("from %s it lands on %s", async (from, to) => {
+ window.history.replaceState({}, "", from);
+
+ render(<LogoutPage />);
+
+ await waitFor(() => expect(mockReplace).toHaveBeenCalledWith(to), {
+ timeout: 3000,
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/logout/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/logout/page.tsx
index 595e9b7f0b..706cef88a4 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/logout/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/logout/page.tsx
@@ -3,6 +3,7 @@
import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
import { Text } from "@/components/atoms/Text/Text";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { getPostLogoutPath } from "@/lib/auth/account-banned";
import { useAuth } from "@/lib/auth/hooks/useAuth";
import { useRouter } from "next/navigation";
import { useEffect, useRef } from "react";
@@ -36,7 +37,7 @@ export default function LogoutPage() {
});
} finally {
await wait(LOGOUT_REDIRECT_DELAY_MS);
- router.replace("/login");
+ router.replace(getPostLogoutPath(window.location.search));
}
}
diff --git a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
index 095c2c9651..fef9eefac8 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/impersonation", () => ({
getSystemHeaders: vi.fn(),
@@ -402,3 +402,64 @@ describe("customMutator — response dates", () => {
);
});
});
+
+describe("customMutator — banned account", () => {
+ let replace: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockIsClientSide.mockReturnValue(true);
+ mockGetSystemHeaders.mockReturnValue({});
+ mockGetTraceData.mockReturnValue({});
+ replace = vi
+ .spyOn(window.location, "replace")
+ .mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ replace.mockRestore();
+ });
+
+ function respondWith(status: number, body: unknown) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ status,
+ statusText: "",
+ headers: new Headers({ "content-type": "application/json" }),
+ json: () => Promise.resolve(body),
+ }),
+ );
+ }
+
+ it("signs the user out on the banned 403", async () => {
+ respondWith(403, {
+ detail: {
+ code: "account_banned",
+ message: "This account has been banned.",
+ },
+ });
+
+ await expect(customMutator("/api/foo", { method: "GET" })).rejects.toThrow(
+ "This account has been banned.",
+ );
+ expect(replace).toHaveBeenCalledWith("/logout?reason=banned");
+ });
+
+ it.each([
+ ["another 403", 403, { detail: "Admin access required" }],
+ [
+ "the banned code on another status",
+ 401,
+ { detail: { code: "account_banned" } },
+ ],
+ ])("leaves the user signed in on %s", async (_, status, body) => {
+ respondWith(status, body);
+
+ await expect(
+ customMutator("/api/foo", { method: "GET" }),
+ ).rejects.toBeDefined();
+ expect(replace).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
index 806297decb..6ff9e9bc23 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
@@ -5,6 +5,10 @@ import {
} from "@/lib/autogpt-server-api/helpers";
import * as Sentry from "@sentry/nextjs";
+import {
+ isAccountBannedResponse,
+ signOutBannedAccount,
+} from "@/lib/auth/account-banned";
import { getSystemHeaders } from "@/lib/impersonation";
import { getDatafastAttribution } from "@/services/analytics/datafast-attribution";
import { environment } from "@/services/environment";
@@ -177,6 +181,9 @@ export const customMutator = async <
logServerRequestFailure(failure);
} else {
logClientRequestFailure(failure);
+ if (isAccountBannedResponse(response.status, responseData)) {
+ signOutBannedAccount();
+ }
}
throw new ApiError(errorMessage, response.status, responseData);
diff --git a/autogpt_platform/frontend/src/lib/auth/account-banned.ts b/autogpt_platform/frontend/src/lib/auth/account-banned.ts
new file mode 100644
index 0000000000..fe51dabd5f
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/account-banned.ts
@@ -0,0 +1,34 @@
+// The backend's `ACCOUNT_BANNED_DETAIL` (autogpt_libs/auth/dependencies.py).
+const ACCOUNT_BANNED_CODE = "account_banned";
+
+const LOGOUT_REASON_PARAM = "reason";
+const ACCOUNT_NOTICE_PARAM = "account";
+const BANNED = "banned";
+
+export function isAccountBannedResponse(status: number, body: unknown) {
+ if (status !== 403 || typeof body !== "object" || body === null) return false;
+ const detail = (body as { detail?: unknown }).detail;
+ return (
+ typeof detail === "object" &&
+ detail !== null &&
+ (detail as { code?: unknown }).code === ACCOUNT_BANNED_CODE
+ );
+}
+
+// Through /logout for the full sign-out; every refused request lands here, so
+// only the first one navigates.
+export function signOutBannedAccount() {
+ if (window.location.pathname === "/logout") return;
+ window.location.replace(`/logout?${LOGOUT_REASON_PARAM}=${BANNED}`);
+}
+
+export function getPostLogoutPath(search: string) {
+ const reason = new URLSearchParams(search).get(LOGOUT_REASON_PARAM);
+ return reason === BANNED
+ ? `/login?${ACCOUNT_NOTICE_PARAM}=${BANNED}`
+ : "/login";
+}
+
+export function isBannedNotice(searchParams: URLSearchParams) {
+ return searchParams.get(ACCOUNT_NOTICE_PARAM) === BANNED;
+}
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts
index c75b34adff..eecf9166c3 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/auth/actions", () => ({
getWebSocketToken: vi.fn(async () => ({ token: "test-token" })),
@@ -124,6 +124,75 @@ describe("BackendAPI._makeClientRequest 204 handling", () => {
});
});
+describe("BackendAPI on a banned account", () => {
+ const banned = JSON.stringify({
+ detail: {
+ code: "account_banned",
+ message: "This account has been banned.",
+ },
+ });
+ let replace: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ replace = vi
+ .spyOn(window.location, "replace")
+ .mockImplementation(() => undefined);
+ vi.spyOn(globalThis, "fetch").mockImplementation(async () => {
+ return new Response(banned, {
+ status: 403,
+ headers: { "Content-Type": "application/json" },
+ });
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it.each([
+ [
+ "a request",
+ (api: BackendAPI) => (api as any)._makeClientRequest("GET", "/x"),
+ ],
+ [
+ "an upload",
+ (api: BackendAPI) =>
+ (api as any)._uploadFile("/upload", new File(["x"], "x.txt")),
+ ],
+ [
+ "an upload with progress",
+ (api: BackendAPI) => api.uploadFile(new File(["x"], "x.txt")),
+ ],
+ ])("signs the user out when %s is refused", async (_, call) => {
+ vi.stubGlobal("XMLHttpRequest", RefusedXHR);
+
+ await expect(
+ call(new BackendAPI("http://test", "ws://test")),
+ ).rejects.toThrow();
+
+ expect(replace).toHaveBeenCalledWith("/logout?reason=banned");
+ });
+
+ class RefusedXHR {
+ status = 403;
+ responseText = banned;
+ withCredentials = false;
+ upload = { addEventListener() {} };
+ private onLoad: (() => void) | undefined;
+
+ addEventListener(type: string, listener: () => void) {
+ if (type === "load") this.onLoad = listener;
+ }
+
+ open() {}
+
+ send() {
+ this.onLoad?.();
+ }
+ }
+});
+
describe("BackendAPI WebSocket failure logging", () => {
const sockets: FakeWebSocket[] = [];
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 61da0f3552..0cb93b31c5 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -1,4 +1,8 @@
import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";
+import {
+ isAccountBannedResponse,
+ signOutBannedAccount,
+} from "@/lib/auth/account-banned";
import { getWebSocketToken } from "@/lib/auth/actions";
import { ImpersonationState } from "@/lib/impersonation";
import { getDatafastAttribution } from "@/services/analytics/datafast-attribution";
@@ -730,7 +734,11 @@ export default class BackendAPI {
});
if (!response.ok) {
- throw await handleFetchError(response);
+ const error = await handleFetchError(response);
+ if (isAccountBannedResponse(error.status, error.response)) {
+ signOutBannedAccount();
+ }
+ throw error;
}
return await response.json();
@@ -791,6 +799,9 @@ export default class BackendAPI {
let errorMessage = `Upload failed (${xhr.status})`;
try {
const errorData = JSON.parse(xhr.responseText);
+ if (isAccountBannedResponse(xhr.status, errorData)) {
+ signOutBannedAccount();
+ }
if (errorData.detail) {
if (
typeof errorData.detail === "string" &&
@@ -901,6 +912,9 @@ export default class BackendAPI {
if (!response.ok) {
const error = await handleFetchError(response);
+ if (isAccountBannedResponse(error.status, error.response)) {
+ signOutBannedAccount();
+ }
if (
isAuthenticationError(response, error.message) &&
isLogoutInProgress()