Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(wizard): flag-driven blocklist for gateway abuse (#94482)

Brandon50221977ca97
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 67d414b0fe87..eca82e7d61dd 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -3178,6 +3178,115 @@ class TestOAuthAPI(APIBaseTest):
code = parse_qs(urlparse(location).query)["code"][0]
return OAuthGrant.objects.get(code=code)
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=True)
+ def test_authorize_refuses_a_blocklisted_identity_a_gateway_scope(self, mock_blocked):
+ # The legacy gateway authenticates the token straight from the database, so
+ # a ban has to stop it being issued, not only its use.
+ app = self._create_first_party_app_with_ceiling("insight:read", "llm_gateway:read")
+ url = self.replace_param_in_url(self.base_authorization_url, "client_id", app.client_id)
+
+ response = self.client.get(f"{url}&scope=insight:read llm_gateway:read")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ self.assertEqual(response.json()["error"], "access_denied")
+ self.assertFalse(OAuthGrant.objects.filter(application=app).exists())
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=True)
+ def test_authorize_still_grants_a_blocklisted_identity_scopes_without_the_gateway(self, mock_blocked):
+ app = self._create_first_party_app_with_ceiling("insight:read")
+
+ grant = self._first_party_authorize_grant(app, "insight:read")
+
+ self.assertEqual(set(grant.scope.split()), {"insight:read"})
+ mock_blocked.assert_not_called()
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=True)
+ def test_authorize_post_refuses_a_blocklisted_identity_a_gateway_scope(self, mock_blocked):
+ # The only caller passing scopes as a raw string, so it is what proves the
+ # normalisation: a bare set() would intersect nothing.
+ app = self._create_first_party_app_with_ceiling("insight:read", "llm_gateway:read")
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ **self.base_authorization_post_body,
+ "client_id": app.client_id,
+ "scope": "insight:read llm_gateway:read",
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ self.assertEqual(response.json()["error"], "access_denied")
+ self.assertFalse(OAuthGrant.objects.filter(application=app).exists())
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=True)
+ def test_authorize_post_refuses_a_blocklisted_identity_a_wildcard_scope(self, mock_blocked):
+ # An app with no ceiling keeps `*` verbatim, the shape a self-registered
+ # client has, and the legacy gateway authenticates it.
+ app = self._create_first_party_app_with_ceiling()
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {**self.base_authorization_post_body, "client_id": app.client_id, "scope": "*"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ self.assertFalse(OAuthGrant.objects.filter(application=app).exists())
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=False)
+ def test_authorize_asks_about_every_organization_the_grant_reaches(self, mock_blocked):
+ # An unscoped first-party grant reaches every organization its user belongs
+ # to, so a ban naming one of them has to be asked about.
+ app = self._create_first_party_app_with_ceiling("llm_gateway:read")
+ url = self.replace_param_in_url(self.base_authorization_url, "client_id", app.client_id)
+
+ self.client.get(f"{url}&scope=llm_gateway:read")
+
+ kwargs = mock_blocked.call_args.kwargs
+ self.assertIn(str(self.organization.id), kwargs["organization_ids"])
+ self.assertEqual(kwargs["user_uuid"], str(self.user.uuid))
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=False)
+ def test_authorize_post_carries_the_grants_own_organization_scoping(self, mock_blocked):
+ # Without this the grant's organizations never reach the flag, so a ban
+ # keyed on one silently matches nothing at issuance.
+ app = self._create_first_party_app_with_ceiling("llm_gateway:read")
+
+ self.client.post(
+ "/oauth/authorize/",
+ {
+ **self.base_authorization_post_body,
+ "client_id": app.client_id,
+ "scope": "llm_gateway:read",
+ "access_level": OAuthApplicationAccessLevel.ORGANIZATION.value,
+ "scoped_organizations": [str(self.organization.id)],
+ },
+ )
+
+ self.assertEqual(mock_blocked.call_args.kwargs["organization_ids"], [str(self.organization.id)])
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=True)
+ def test_authorize_post_still_grants_scopes_without_a_gateway_scope(self, mock_blocked):
+ app = self._create_first_party_app_with_ceiling("insight:read")
+
+ response = self.client.post(
+ "/oauth/authorize/",
+ {**self.base_authorization_post_body, "client_id": app.client_id, "scope": "insight:read"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ mock_blocked.assert_not_called()
+
+ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=False)
+ def test_authorize_grants_the_gateway_scope_to_an_unlisted_identity(self, mock_blocked):
+ app = self._create_first_party_app_with_ceiling("insight:read", "llm_gateway:read")
+
+ grant = self._first_party_authorize_grant(app, "insight:read llm_gateway:read")
+
+ self.assertIn("llm_gateway:read", grant.scope.split())
+ self.assertEqual(mock_blocked.call_args.kwargs["surface"], "oauth_authorize")
+ self.assertEqual(mock_blocked.call_args.kwargs["email"], self.user.email)
+
def test_authorize_wildcard_narrowed_to_seeded_ceiling(self):
# A `*` request against a seeded ceiling is narrowed to the resolved ceiling
# rather than rejected. First-party apps skip consent, so the grant is the
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 075a104afff6..5ff36539deb4 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -2,6 +2,7 @@ import json
import uuid
import hashlib
import calendar
+from collections.abc import Iterable
from datetime import datetime, timedelta
from typing import TypedDict, cast
from urllib.parse import parse_qs, urlparse
@@ -60,6 +61,7 @@ from posthog.api.oauth.client_assertion import (
from posthog.api.oauth.client_auth import verify_client_secret
from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
+from posthog.llm.wizard_blocklist import GATEWAY_BEARING_SCOPES, WIZARD_BLOCKED_DETAIL, wizard_identity_blocked
from posthog.middleware import is_read_only_impersonation
from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User
from posthog.models.oauth import (
@@ -268,6 +270,48 @@ def _impersonation_ai_processing_block(
)
+def _gateway_blocklist_block(
+ request,
+ scopes: str | Iterable[str],
+ *,
+ access_level: str | None = None,
+ scoped_organization_ids: list[str] | None = None,
+ scoped_team_ids: list[int] | None = None,
+) -> Response | None:
+ """Refuse a blocklisted identity a grant carrying an LLM gateway scope.
+
+ Keyed on the scope rather than the wizard's client id, so another first-party
+ app whose ceiling includes it is not an evasion route.
+
+ Asked against every organization the grant would reach, so a ban naming one of
+ them refuses a credential that bundles it with others.
+
+ Refuses the whole authorization rather than dropping the scope, so a ban costs
+ a bundled client its sign-in too. Deliberate for an abuse ban, and the one
+ departure from this module's clamp-don't-reject policy. Returns a 403 to
+ short-circuit with, or None.
+ """
+ # One caller holds the scopes as a list, another as the raw space-delimited
+ # string, which a bare set() would degrade into characters matching nothing.
+ requested = set(scopes.split() if isinstance(scopes, str) else scopes)
+ if not GATEWAY_BEARING_SCOPES & requested:
+ return None
+ organization_ids = _scoped_organization_ids(request.user, access_level, scoped_organization_ids, scoped_team_ids)
+ if not wizard_identity_blocked(
+ distinct_id=str(request.user.distinct_id),
+ email=request.user.email,
+ surface="oauth_authorize",
+ user_uuid=str(request.user.uuid),
+ organization_ids=[str(organization_id) for organization_id in organization_ids],
+ team_ids=scoped_team_ids or [],
+ ):
+ return None
+ return Response(
+ {"error": "access_denied", "error_description": WIZARD_BLOCKED_DETAIL},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+
class OAuthAuthorizationContext(TypedDict):
user: User
@@ -1363,6 +1407,8 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
if application.is_first_party:
if block := _impersonation_ai_processing_block(request):
return block
+ if block := _gateway_blocklist_block(request, scope_str.split()):
+ return block
try:
org_ids = request.user.organizations.values_list("id", flat=True)
credentials["scoped_organizations"] = [str(org_id) for org_id in org_ids]
@@ -1400,6 +1446,8 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# matched token's scope through — the precise check lives in the POST path.
if block := _impersonation_ai_processing_block(request):
return block
+ if block := _gateway_blocklist_block(request, scope_str.split()):
+ return block
uri, headers, body, status_code = self.create_authorization_response(
request=request, scopes=scope_str, credentials=credentials, allow=True
)
@@ -1512,6 +1560,15 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
):
return block
+ if block := _gateway_blocklist_block(
+ request,
+ scopes,
+ access_level=serializer.validated_data.get("access_level"),
+ scoped_organization_ids=serializer.validated_data.get("scoped_organizations"),
+ scoped_team_ids=serializer.validated_data.get("scoped_teams"),
+ ):
+ return block
+
try:
uri, headers, body, status_code = self.create_authorization_response(
request=request,
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.py
index 4eb36fddbc24..9a778e82af20 100644
--- a/posthog/api/wizard/http.py
+++ b/posthog/api/wizard/http.py
@@ -31,6 +31,7 @@ from posthog.api.wizard.utils import json_schema_to_gemini_schema
from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
from posthog.cloud_utils import get_api_host
from posthog.exceptions_capture import capture_exception
+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blocked
from posthog.llm.wizard_gateway_token import (
WizardGatewayMintError,
mint_wizard_gateway_token,
@@ -79,8 +80,8 @@ WIZARD_CLOUD_RUN_DAILY_ATTEMPT_CAP = 15
WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL = Counter(
"posthog_wizard_gateway_token_requests_total",
"Wizard gateway-token mint requests, by outcome (minted/unconfigured/not_wizard_app/"
- "scope_missing/team_ambiguous/team_missing/unauthorized/program_unknown/not_rolled_out/"
- "mint_failed)",
+ "scope_missing/team_ambiguous/team_missing/unauthorized/blocked/program_unknown/"
+ "not_rolled_out/mint_failed)",
labelnames=["outcome"],
)
@@ -101,6 +102,21 @@ ALL_SUPPORTED_MODELS = OPENAI_SUPPORTED_MODELS | GEMINI_SUPPORTED_MODELS
MODEL_SEED = 7678464
+def _organization_ids_for_query(team_ids: list[int]) -> list[str]:
+ """The organizations the request itself pins.
+
+ Deliberately not the user's current organization, which is writable through
+ `PATCH /api/users/@me/`: a ban keyed on it would let the banned account switch
+ itself out of the match.
+ """
+ if not team_ids:
+ return []
+ return [
+ str(organization_id)
+ for organization_id in Team.objects.filter(id__in=team_ids).values_list("organization_id", flat=True).distinct()
+ ]
+
+
class SetupWizardSerializer(serializers.Serializer):
hash = serializers.CharField()
@@ -268,6 +284,8 @@ class SetupWizardViewSet(viewsets.ViewSet):
distinct_id = wizard_data.get("user_distinct_id")
team_id = wizard_data.get("team_id")
+ blocklist_team_ids = [team_id] if team_id else []
+ blocklist_user = None
trace_id = trace_id or hashlib.sha256(hash.encode()).hexdigest()
@@ -286,8 +304,28 @@ class SetupWizardViewSet(viewsets.ViewSet):
distinct_id = user.distinct_id
scoped_team_ids = authenticator.access_token.scoped_teams or []
team_id = scoped_team_ids[0] if len(scoped_team_ids) == 1 else None
+ # Every scoped team, not the sole one `team_id` narrows to: a token
+ # spanning several still grants each, so a ban naming one must match.
+ blocklist_team_ids = list(scoped_team_ids)
trace_id = request.headers.get("X-PostHog-Trace-Id") or hashlib.sha256(distinct_id.encode()).hexdigest()
+ blocklist_user = user
+
+ if blocklist_user is None:
+ # The hash path proves a distinct_id, not a user, and the ban list is
+ # written against addresses.
+ blocklist_user = User.objects.filter(distinct_id=distinct_id).first()
+ if wizard_identity_blocked(
+ distinct_id=str(distinct_id),
+ email=blocklist_user.email if blocklist_user else None,
+ user_uuid=str(blocklist_user.uuid) if blocklist_user else "",
+ organization_ids=_organization_ids_for_query(blocklist_team_ids),
+ team_ids=blocklist_team_ids,
+ surface="query",
+ ):
+ # No outcome label: query labels no other exit, and the blocklist
+ # counter already carries this surface with its own denominator.
+ raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)
posthog_client = posthoganalytics.default_client
@@ -474,6 +512,19 @@ class SetupWizardViewSet(viewsets.ViewSet):
raise exceptions.PermissionDenied("Access token is no longer authorized for this project.")
distinct_id = str(user.distinct_id)
+ if wizard_identity_blocked(
+ distinct_id=distinct_id,
+ email=user.email,
+ user_uuid=str(user.uuid),
+ organization_ids=[str(team.organization_id)],
+ team_ids=[team.id],
+ surface="gateway_token",
+ ):
+ # 403 and not 404, ahead of the rollout gate: the CLI reads 404 as "stay
+ # on legacy", moving a banned run onto the looser surface.
+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="blocked").inc()
+ raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)
+
if not posthoganalytics.feature_enabled(
"wizard-gateway-v2",
distinct_id,
@@ -669,7 +720,22 @@ class SetupWizardViewSet(viewsets.ViewSet):
if project.id not in visible_project_ids:
raise exceptions.PermissionDenied("You don't have access to this project.")
- self._reserve_cloud_run_attempt(cast(User, request.user).id)
+ user = cast(User, request.user)
+ # The sandbox this starts mints its own gateway token. Refused before the
+ # attempt is reserved, so a ban does not also cost a daily slot.
+ if wizard_identity_blocked(
+ distinct_id=str(user.distinct_id),
+ email=user.email,
+ user_uuid=str(user.uuid),
+ organization_ids=[str(project.organization_id)],
+ team_ids=[project.id],
+ surface="cloud_run",
+ ):
+ # No outcome label: `cloud_run` already counts every PermissionDenied as
+ # permission_denied.
+ raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)
+
+ self._reserve_cloud_run_attempt(user.id)
try:
result = tasks_facade.create_wizard_cloud_run(
diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.py
index b3115bf827ea..0f616ee94a52 100644
--- a/posthog/api/wizard/test/test_http.py
+++ b/posthog/api/wizard/test/test_http.py
@@ -19,6 +19,7 @@ from rest_framework.test import APIRequestFactory
from posthog.api.wizard.http import SETUP_WIZARD_CACHE_PREFIX, SETUP_WIZARD_CACHE_TIMEOUT
from posthog.cloud_utils import get_api_host
+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL
from posthog.llm.wizard_gateway_token import WizardGatewayMintError
from posthog.models import Organization, PersonalAPIKey, User
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -27,6 +28,12 @@ from posthog.rate_limit import SetupWizardGatewayTokenRateThrottle, refund_wizar
class SetupWizardTests(APIBaseTest):
def setUp(self):
+ # Patched at the endpoint's seam: these tests replace default_client with a
+ # MagicMock that module-level feature_enabled delegates to, so an unpatched
+ # flag call reads truthy and every query 403s.
+ blocklist_patch = patch("posthog.api.wizard.http.wizard_identity_blocked", return_value=False)
+ self.mock_blocklist = blocklist_patch.start()
+ self.addCleanup(blocklist_patch.stop)
self.initialize_url = reverse("wizard-initialize")
self.data_url = reverse("wizard-data")
self.query_url = reverse("wizard-query")
@@ -38,6 +45,60 @@ class SetupWizardTests(APIBaseTest):
SETUP_WIZARD_CACHE_TIMEOUT,
)
+ @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())
+ @patch("posthog.api.wizard.http.OpenAI")
+ def test_query_from_a_blocked_identity_is_403(self, mock_openai):
+ self.mock_blocklist.return_value = True
+ response = self.client.post(
+ self.query_url,
+ data=json.dumps(
+ {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}
+ ),
+ content_type="application/json",
+ headers={"x-posthog-wizard-hash": self.hash},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL
+ # The proxy spends PostHog's own provider keys.
+ mock_openai.return_value.chat.completions.create.assert_not_called()
+
+ @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())
+ @patch("posthog.api.wizard.http.OpenAI")
+ def test_query_resolves_the_address_behind_the_hash(self, mock_openai):
+ # The hash proves a distinct_id only, and a domain ban needs the address.
+ cache.set(
+ self.cache_key,
+ {
+ "project_api_key": "test-key",
+ "host": "http://localhost:8010",
+ "team_id": self.team.id,
+ "user_distinct_id": str(self.user.distinct_id),
+ },
+ SETUP_WIZARD_CACHE_TIMEOUT,
+ )
+ mock_openai.return_value.chat.completions.create.return_value = MagicMock(
+ choices=[MagicMock(message=MagicMock(content=json.dumps({"foo": "bar"})))]
+ )
+
+ self.client.post(
+ self.query_url,
+ data=json.dumps(
+ {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}
+ ),
+ content_type="application/json",
+ headers={"x-posthog-wizard-hash": self.hash},
+ )
+
+ assert self.mock_blocklist.call_args.kwargs == {
+ "distinct_id": str(self.user.distinct_id),
+ "email": self.user.email,
+ "user_uuid": str(self.user.uuid),
+ "organization_ids": [str(self.team.organization_id)],
+ "team_ids": [self.team.id],
+ "surface": "query",
+ }
+
def test_initialize_creates_hash(self):
response = self.client.post(self.initialize_url)
assert response.status_code == status.HTTP_200_OK
@@ -507,6 +568,18 @@ class SetupWizardTests(APIBaseTest):
class SetupWizardCloudRunTests(APIBaseTest):
CLOUD_RUN_URL = "/api/wizard/cloud_run"
+ @patch("posthog.api.wizard.http.wizard_identity_blocked", return_value=True)
+ def test_a_blocked_identity_cannot_start_a_cloud_run(self, mock_blocked):
+ # The sandbox mints its own gateway token.
+ response = self.client.post(
+ self.CLOUD_RUN_URL,
+ {"project_id": self.team.project_id, "repository": "PostHog/posthog"},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL
+ assert mock_blocked.call_args.kwargs["surface"] == "cloud_run"
+
@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="")
def test_returns_404_when_feature_not_configured(self):
response = self.client.post(
@@ -679,6 +752,12 @@ class SetupWizardGatewayTokenTests(APIBaseTest):
)
self.mock_limit_payload = payload_patch.start()
self.addCleanup(payload_patch.stop)
+ # Patched at the endpoint's seam: the feature_enabled patches below land on
+ # the shared module object, so an SDK-level patch would read the rollout
+ # flag's value as a ban.
+ blocklist_patch = patch("posthog.api.wizard.http.wizard_identity_blocked", return_value=False)
+ self.mock_blocklist = blocklist_patch.start()
+ self.addCleanup(blocklist_patch.stop)
def tearDown(self):
super().tearDown()
@@ -729,6 +808,76 @@ class SetupWizardGatewayTokenTests(APIBaseTest):
response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})
assert response.status_code == status.HTTP_404_NOT_FOUND
+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)
+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)
+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")
+ def test_blocked_identity_is_403_and_never_mints(self, mock_authentication, mock_flag, mock_mint, mock_authorized):
+ # 403 rather than 404, which the CLI reads as "stay on legacy".
+ self._mock_oauth(mock_authentication)
+ self.mock_blocklist.return_value = True
+
+ response = self.client.post(
+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL
+ mock_mint.assert_not_called()
+
+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)
+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)
+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=False)
+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")
+ def test_a_ban_outranks_the_rollout_gate(self, mock_authentication, mock_flag, mock_mint, mock_authorized):
+ # Not-rolled-out answers 404 and downgrades to legacy, so the ban has to
+ # land first whatever the rollout says.
+ self._mock_oauth(mock_authentication)
+ self.mock_blocklist.return_value = True
+
+ response = self.client.post(
+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+
+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)
+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)
+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")
+ def test_the_ban_is_asked_about_the_authenticated_identity(
+ self, mock_authentication, mock_flag, mock_mint, mock_authorized
+ ):
+ self._mock_oauth(mock_authentication)
+
+ self.client.post(
+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}
+ )
+
+ assert self.mock_blocklist.call_args.kwargs == {
+ "distinct_id": str(self.user.distinct_id),
+ "email": self.user.email,
+ "user_uuid": str(self.user.uuid),
+ "organization_ids": [str(self.team.organization_id)],
+ "team_ids": [self.team.id],
+ "surface": "gateway_token",
+ }
+
+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)
+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)
+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")
+ def test_a_ban_is_counted(self, mock_authentication, mock_flag, mock_mint, mock_authorized):
+ self._mock_oauth(mock_authentication)
+ self.mock_blocklist.return_value = True
+ before = _gateway_token_outcome("blocked")
+
+ self.client.post(
+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}
+ )
+
+ assert _gateway_token_outcome("blocked") == before + 1
+
@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")
def test_missing_gateway_scope_is_401(self, mock_authentication):
# "*" must not subsume the privileged scope.
diff --git a/posthog/llm/test_wizard_blocklist.py b/posthog/llm/test_wizard_blocklist.py
new file mode 100644
index 000000000000..0775399ed384
--- /dev/null
+++ b/posthog/llm/test_wizard_blocklist.py
@@ -0,0 +1,317 @@
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from posthog.llm.wizard_blocklist import (
+ _team_organizations,
+ blocklist_flag_defined,
+ blocklist_properties,
+ wizard_identity_blocked,
+)
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+
+
+class TestBlocklistProperties:
+ @pytest.mark.parametrize(
+ "email,expected_root,expected_domain",
+ [
+ ("[email protected]", "[email protected]", "gmail.com"),
+ ("[email protected]", "[email protected]", "gmail.com"),
+ ("[email protected]", "[email protected]", "googlemail.com"),
+ (" [email protected] ", "[email protected]", "gmail.com"),
+ # Dots alias only at Gmail; elsewhere they identify the mailbox.
+ ("[email protected]", "[email protected]", "example.net"),
+ ("[email protected]", "[email protected]", "example.com"),
+ ("[email protected]", "@example.org", "example.org"),
+ ('"a@b"@example.net', '"a@b"@example.net', "example.net"),
+ ],
+ )
+ def test_derives_the_keys_an_abuse_report_names(self, email, expected_root, expected_domain):
+ properties = blocklist_properties(email=email, organization_id="org_1", team_id=7)
+
+ assert properties["email"] == email.strip().lower()
+ assert properties["email_root"] == expected_root
+ assert properties["email_domain"] == expected_domain
+
+ @pytest.mark.parametrize("email", [None, "", " ", "nodomain"])
+ def test_an_unusable_address_still_carries_every_key(self, email):
+ properties = blocklist_properties(email=email, organization_id="org_1", team_id=7)
+
+ # A missing key would make a condition on it silently never match.
+ assert set(properties) == {"user_uuid", "email", "email_root", "email_domain", "organization_id", "team_id"}
+ assert properties["email_domain"] == ""
+ assert properties["organization_id"] == "org_1"
+ assert properties["team_id"] == "7"
+
+
+class TestWizardIdentityBlocked:
+ def test_evaluates_the_flag_with_every_match_key(self):
+ with patch(
+ "posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=True
+ ) as feature_enabled:
+ blocked = wizard_identity_blocked(
+ distinct_id="d1",
+ user_uuid="uuid-1",
+ organization_ids=["org_1"],
+ team_ids=[7],
+ surface="gateway_token",
+ )
+
+ assert blocked is True
+ feature_enabled.assert_called_once_with(
+ "wizard-gateway-blocklist",
+ "d1",
+ person_properties={
+ "user_uuid": "uuid-1",
+ "email": "[email protected]",
+ "email_root": "[email protected]",
+ "email_domain": "example.com",
+ "organization_id": "org_1",
+ "team_id": "7",
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+
+ def test_an_unlisted_identity_is_not_blocked(self):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=False):
+ assert (
+ wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1"],
+ team_ids=[7],
+ surface="gateway_token",
+ )
+ is False
+ )
+
+ def test_the_lookup_never_leaves_the_process(self):
+ # A gate on /oauth/authorize must not add an outbound call to every grant.
+ with patch(
+ "posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=True
+ ) as feature_enabled:
+ wizard_identity_blocked(distinct_id="d1", email="[email protected]", surface="revoke_sweep")
+
+ assert feature_enabled.call_args.kwargs["only_evaluate_locally"] is True
+
+ def test_an_undecidable_flag_is_counted_apart_from_an_unlisted_identity(self):
+ with (
+ patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=None),
+ patch("posthog.llm.wizard_blocklist.blocklist_flag_defined", return_value=True),
+ patch("posthog.llm.wizard_blocklist.WIZARD_BLOCKLIST_CHECKS") as checks,
+ ):
+ assert wizard_identity_blocked(distinct_id="d1", email="[email protected]", surface="query") is False
+
+ assert checks.labels.call_args.kwargs == {"surface": "query", "outcome": "inconclusive"}
+
+ def test_a_missing_flag_is_not_reported_as_undecidable(self):
+ with (
+ patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=None),
+ patch("posthog.llm.wizard_blocklist.blocklist_flag_defined", return_value=False),
+ patch("posthog.llm.wizard_blocklist.WIZARD_BLOCKLIST_CHECKS") as checks,
+ ):
+ wizard_identity_blocked(distinct_id="d1", email="[email protected]", surface="query")
+
+ assert checks.labels.call_args.kwargs == {"surface": "query", "outcome": "unconfigured"}
+
+ def test_an_unknown_org_and_team_still_carry_their_keys(self):
+ properties = blocklist_properties(email="[email protected]")
+
+ # OAuth consent pins no project, and an address ban still has to land.
+ assert properties["organization_id"] == ""
+ assert properties["team_id"] == ""
+ assert properties["email_domain"] == "example.com"
+
+ @pytest.mark.parametrize("outcome", [{"side_effect": RuntimeError("down")}, {"return_value": None}])
+ def test_a_flag_outage_fails_open(self, outcome):
+ # Losing the blocklist must not refuse every wizard run.
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", **outcome):
+ assert (
+ wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1"],
+ team_ids=[7],
+ surface="gateway_token",
+ )
+ is False
+ )
+
+
+class TestBlocklistFlagDefined:
+ @pytest.mark.parametrize(
+ "definitions,expected",
+ [
+ # The SDK returns data["flags"] verbatim: a list of dicts, or None
+ # before local evaluation has loaded any.
+ ([{"key": "wizard-gateway-blocklist"}, {"key": "other"}], True),
+ ([{"key": "other"}], False),
+ ([], False),
+ (None, False),
+ ({"flags": [{"key": "wizard-gateway-blocklist"}]}, True),
+ ],
+ )
+ def test_reads_the_shape_the_sdk_actually_returns(self, definitions, expected):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_flag_definitions", return_value=definitions):
+ assert blocklist_flag_defined() is expected
+
+ def test_an_sdk_error_is_not_a_definition(self):
+ with patch(
+ "posthog.llm.wizard_blocklist.posthoganalytics.feature_flag_definitions",
+ side_effect=RuntimeError("down"),
+ ):
+ assert blocklist_flag_defined() is False
+
+
+class TestMatchContexts:
+ """A credential grants every organization it is scoped to, so each is asked."""
+
+ def test_a_ban_naming_one_of_several_organizations_still_matches(self):
+ # Only the second organization is named, and the sole-organization reading
+ # of this credential would be "" and miss it.
+ def only_org_2(_flag, _distinct_id, *, person_properties, **_kwargs):
+ return person_properties["organization_id"] == "org_2"
+
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", side_effect=only_org_2):
+ blocked = wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1", "org_2", "org_3"],
+ surface="revoke_sweep",
+ )
+
+ assert blocked is True
+
+ def test_an_unnamed_organization_set_is_allowed(self):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=False) as enabled:
+ blocked = wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1", "org_2"],
+ surface="revoke_sweep",
+ )
+
+ assert blocked is False
+ assert enabled.call_count == 2
+
+ def test_an_organization_and_team_pair_is_asked_together(self):
+ # A condition naming both only matches while they arrive in one question.
+ def org_1_and_team_7(_flag, _distinct_id, *, person_properties, **_kwargs):
+ return person_properties["organization_id"] == "org_1" and person_properties["team_id"] == "7"
+
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", side_effect=org_1_and_team_7):
+ blocked = wizard_identity_blocked(
+ distinct_id="d1", email="[email protected]", organization_ids=["org_1"], team_ids=[7], surface="query"
+ )
+
+ assert blocked is True
+
+ def test_several_organizations_and_teams_pair_each_team_with_its_owner(self):
+ # A condition naming an organization and a team together only matches while
+ # they arrive in one question, and the cartesian would ban a combination the
+ # credential never granted.
+ seen = []
+
+ def record(_flag, _distinct_id, *, person_properties, **_kwargs):
+ seen.append((person_properties["organization_id"], person_properties["team_id"]))
+ return False
+
+ with patch("posthog.llm.wizard_blocklist._team_organizations", return_value={7: "org_1", 8: "org_2"}):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", side_effect=record):
+ wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1", "org_2"],
+ team_ids=[7, 8],
+ surface="revoke_sweep",
+ )
+
+ assert seen == [("org_1", "7"), ("org_2", "8")]
+
+ def test_an_organization_no_team_accounts_for_is_still_asked_about(self):
+ seen = []
+
+ def record(_flag, _distinct_id, *, person_properties, **_kwargs):
+ seen.append((person_properties["organization_id"], person_properties["team_id"]))
+ return False
+
+ with patch("posthog.llm.wizard_blocklist._team_organizations", return_value={7: "org_1"}):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", side_effect=record):
+ wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1", "org_2"],
+ team_ids=[7, 8],
+ surface="revoke_sweep",
+ )
+
+ # org_2 is reachable through the credential but owns no scoped team.
+ assert seen == [("org_1", "7"), ("", "8"), ("org_2", "")]
+
+ def test_one_outcome_is_recorded_per_check_not_per_context(self):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", return_value=False):
+ with patch("posthog.llm.wizard_blocklist.record_blocklist_outcome") as record:
+ wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1", "org_2", "org_3"],
+ surface="revoke_sweep",
+ )
+
+ record.assert_called_once_with("revoke_sweep", "allowed")
+
+
+class TestImmutableMatchKey:
+ def test_the_account_uuid_is_a_match_key_an_address_change_cannot_shed(self):
+ # An email-keyed ban follows the mailbox; this one follows the account.
+ def only_uuid(_flag, _distinct_id, *, person_properties, **_kwargs):
+ return person_properties["user_uuid"] == "uuid-1"
+
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", side_effect=only_uuid):
+ blocked = wizard_identity_blocked(
+ distinct_id="d1", email="[email protected]", user_uuid="uuid-1", surface="oauth_authorize"
+ )
+
+ assert blocked is True
+
+
+class TestTeamOrganizations(APIBaseTest):
+ def test_each_team_resolves_to_the_organization_that_owns_it(self):
+ # The pairing is only correct while this reads real ownership; a credential
+ # carries the teams but never says which organization each one sits in.
+ other_organization = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_organization, name="Other team")
+
+ owners = _team_organizations([self.team.id, other_team.id])
+
+ assert owners == {
+ self.team.id: str(self.team.organization_id),
+ other_team.id: str(other_organization.id),
+ }
+
+
+class TestFailOpen:
+ def test_unreadable_team_ownership_degrades_instead_of_raising(self):
+ # The module refuses nobody when a lookup breaks; raising here would 500
+ # the authorize and query paths instead.
+ seen = []
+
+ def record(_flag, _distinct_id, *, person_properties, **_kwargs):
+ seen.append((person_properties["organization_id"], person_properties["team_id"]))
+ return False
+
+ with patch("posthog.llm.wizard_blocklist._team_organizations", side_effect=OSError("db down")):
+ with patch("posthog.llm.wizard_blocklist.posthoganalytics.feature_enabled", side_effect=record):
+ blocked = wizard_identity_blocked(
+ distinct_id="d1",
+ organization_ids=["org_1", "org_2"],
+ team_ids=[7, 8],
+ surface="revoke_sweep",
+ )
+
+ assert blocked is False
+ assert seen == [("", "7"), ("", "8"), ("org_1", ""), ("org_2", "")]
diff --git a/posthog/llm/wizard_blocklist.py b/posthog/llm/wizard_blocklist.py
new file mode 100644
index 000000000000..5b89690142f5
--- /dev/null
+++ b/posthog/llm/wizard_blocklist.py
@@ -0,0 +1,208 @@
+"""Refuse a wizard identity the abuse blocklist names.
+
+The list lives in the flag's conditions: Django derives the match keys and passes
+them as person properties, so a ban is a flag edit rather than a deploy.
+
+Evaluation is local-only, because a gate on `/oauth/authorize` must not add an
+outbound request to every OAuth grant. That makes the flag's shape part of the
+contract: a cohort condition cannot be evaluated locally, and `inconclusive` is
+what surfaces that rather than letting it read as "nobody is banned". A flag
+outage fails open, since losing the blocklist must not refuse every wizard run.
+"""
+
+from collections.abc import Iterable
+
+import structlog
+import posthoganalytics
+from prometheus_client import Counter
+
+from posthog.models.team.team import Team
+from posthog.scopes import PRIVILEGED_SCOPES
+
+logger = structlog.get_logger(__name__)
+
+# Conditions read `user_uuid`, `email`, `email_root`, `email_domain`,
+# `organization_id` and `team_id`. Every release condition must carry one of them:
+# a group with no properties bans every wizard user rather than the ones named.
+# `user_uuid` is the only key the banned account cannot change; an address can be
+# swapped through `PATCH /api/users/@me/`, so an email key bans a mailbox and
+# `user_uuid` bans the account.
+WIZARD_BLOCKLIST_FLAG = "wizard-gateway-blocklist"
+
+# Wider than the two privileged names: the legacy gateway authenticates a bare
+# `*`, which an app with an empty ceiling is still granted verbatim.
+GATEWAY_BEARING_SCOPES = frozenset(PRIVILEGED_SCOPES | {"*"})
+
+# Gmail ignores dots in the local part, so one mailbox has many spellings.
+_DOT_INSENSITIVE_DOMAINS = frozenset({"gmail.com", "googlemail.com"})
+
+# One string for every surface: the wizard shows it to the user, so a ban reads
+# the same whether it lands at consent, at the mint, or on a query.
+WIZARD_BLOCKED_DETAIL = (
+ "This account is blocked from the PostHog AI gateway for suspected abuse. "
+ "Contact [email protected] if you believe this is a mistake."
+)
+
+# `allowed` is the denominator a block count needs to read as a rate.
+# `unconfigured` is the state before anyone writes the flag; `inconclusive` means
+# a written flag is not enforcing.
+WIZARD_BLOCKLIST_CHECKS = Counter(
+ "posthog_wizard_blocklist_checks_total",
+ "Blocklist checks, by surface and outcome (blocked/allowed/unconfigured/inconclusive)",
+ labelnames=["surface", "outcome"],
+)
+
+
+def blocklist_properties(
+ *, email: str | None, user_uuid: str = "", organization_id: str = "", team_id: int | None = None
+) -> dict[str, str]:
+ """The match keys the flag's conditions read.
+
+ Every key is always present: a condition naming a key we omitted would
+ silently never match. Only `email_root` folds provider aliasing, so banning
+ an `email_domain` matches what an abuse report shows.
+ """
+ address = (email or "").strip().lower()
+ local, at, domain = address.rpartition("@")
+ if not at:
+ # No domain to fold or ban: an address this shape only matches literally.
+ return {
+ "user_uuid": user_uuid,
+ "email": address,
+ "email_root": address,
+ "email_domain": "",
+ "organization_id": organization_id,
+ "team_id": _team_key(team_id),
+ }
+ root_local = local.split("+", 1)[0]
+ root_domain = domain
+ if domain in _DOT_INSENSITIVE_DOMAINS:
+ root_local = root_local.replace(".", "")
+ root_domain = "gmail.com"
+ return {
+ "user_uuid": user_uuid,
+ "email": address,
+ "email_root": f"{root_local}@{root_domain}",
+ "email_domain": domain,
+ "organization_id": organization_id,
+ "team_id": _team_key(team_id),
+ }
+
+
+def _team_key(team_id: int | None) -> str:
+ return "" if team_id is None else str(team_id)
+
+
+def blocklist_flag_defined() -> bool:
+ """Whether local definitions carry the flag, which is how "no ban list exists"
+ is told apart from "the ban list cannot be evaluated". The SDK reports both as
+ None."""
+ try:
+ definitions = posthoganalytics.feature_flag_definitions()
+ except Exception:
+ return False
+ flags = definitions.get("flags", []) if isinstance(definitions, dict) else (definitions or [])
+ return any(isinstance(flag, dict) and flag.get("key") == WIZARD_BLOCKLIST_FLAG for flag in flags)
+
+
+def _match_contexts(organization_ids: Iterable[str], team_ids: Iterable[int]) -> list[tuple[str, int | None]]:
+ """The (organization, team) pairs a credential reaches, asked one at a time.
+
+ A credential scoped to several organizations grants all of them, so collapsing
+ it to a single value would let a ban naming one of them miss.
+ """
+ organizations = list(dict.fromkeys(str(org) for org in organization_ids if str(org)))
+ teams = list(dict.fromkeys(team_ids))
+ if len(organizations) <= 1:
+ organization_id = organizations[0] if organizations else ""
+ return [(organization_id, team_id) for team_id in teams] or [(organization_id, None)]
+ if not teams:
+ return [(organization_id, None) for organization_id in organizations]
+ # Which team sits in which organization is not on the credential, so read it
+ # rather than pairing every organization with every team, which would ban a
+ # combination the credential never granted.
+ try:
+ owners = _team_organizations(teams)
+ except Exception as e:
+ # Fail open like every other lookup here: degrade to asking about each
+ # dimension alone rather than refusing every wizard run.
+ logger.warning("wizard_blocklist: team ownership unavailable", error=str(e))
+ owners = {}
+ contexts = [(owners.get(team_id, ""), team_id) for team_id in teams]
+ paired = {organization_id for organization_id, _ in contexts}
+ return contexts + [(organization_id, None) for organization_id in organizations if organization_id not in paired]
+
+
+def _team_organizations(team_ids: list[int]) -> dict[int, str]:
+ """The organization owning each team, so a condition naming both still matches."""
+ return {
+ team_id: str(organization_id)
+ for team_id, organization_id in Team.objects.filter(id__in=team_ids).values_list("id", "organization_id")
+ }
+
+
+def wizard_identity_blocked(
+ *,
+ distinct_id: str,
+ email: str | None,
+ surface: str,
+ user_uuid: str = "",
+ organization_ids: Iterable[str] = (),
+ team_ids: Iterable[int] = (),
+) -> bool:
+ """True when the blocklist names this identity in any context the credential
+ reaches; anything else answers False.
+
+ One outcome is recorded per call, not per context, so the counter stays a count
+ of identity checks.
+ """
+ unavailable = False
+ unevaluated = False
+ for organization_id, team_id in _match_contexts(organization_ids, team_ids):
+ properties = blocklist_properties(
+ email=email, user_uuid=user_uuid, organization_id=organization_id, team_id=team_id
+ )
+ try:
+ blocked = posthoganalytics.feature_enabled(
+ WIZARD_BLOCKLIST_FLAG,
+ distinct_id,
+ person_properties=properties,
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception as e:
+ unavailable = True
+ logger.warning("wizard_blocklist: flag unavailable", error=str(e), surface=surface)
+ continue
+ if blocked:
+ record_blocklist_outcome(surface, "blocked")
+ # The domain rather than the address, to keep mailboxes out of the logs.
+ # Info rather than warn: refusals are the steady state once a ban is in place.
+ logger.info(
+ "wizard_blocklist: identity refused",
+ surface=surface,
+ email_domain=properties["email_domain"],
+ organization_id=organization_id,
+ team_id=team_id,
+ )
+ return True
+ if blocked is None:
+ # No verdict, which is not the same as "not banned": once the flag exists,
+ # this means its conditions cannot be evaluated in-process.
+ unevaluated = True
+ if unavailable or (unevaluated and blocklist_flag_defined()):
+ record_blocklist_outcome(surface, "inconclusive")
+ if unevaluated and not unavailable:
+ logger.warning("wizard_blocklist: flag could not be evaluated locally", surface=surface)
+ return False
+ if unevaluated:
+ record_blocklist_outcome(surface, "unconfigured")
+ return False
+ record_blocklist_outcome(surface, "allowed")
+ return False
+
+
+def record_blocklist_outcome(surface: str, outcome: str) -> None:
+ """Public so a caller deciding a whole run's outcome, without asking per
+ identity, still reports to the same counter."""
+ WIZARD_BLOCKLIST_CHECKS.labels(surface=surface, outcome=outcome).inc()
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index ea6134cb92ef..1dd98b1a6be5 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -71,6 +71,7 @@ from posthog.tasks.tasks import (
from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_policy_cache_entries
from posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entries
from posthog.tasks.uploaded_media import sweep_abandoned_media_uploads_task
+from posthog.tasks.wizard_blocklist import revoke_blocklisted_gateway_credentials
from posthog.utils import get_crontab, get_instance_region
from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requests
@@ -239,6 +240,16 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="schedule warming for largest teams",
)
+ # Wizard abuse blocklist sweep - every 10 minutes. Consent already refuses a
+ # banned user a new gateway-scoped grant; this is what reaches the credentials
+ # issued before the ban, which is the only thing the legacy gateway reads.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/10"),
+ revoke_blocklisted_gateway_credentials.s(),
+ name="wizard blocklist gateway credential revoke",
+ )
+
# Team metadata cache sync - hourly
sender.add_periodic_task(
crontab(hour="*", minute="0"),
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 27e02e29d3c2..f649607caad8 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -156,5 +156,6 @@
'posthog.tasks.usage_report.send_all_org_usage_reports',
'posthog.tasks.usage_report.send_report_to_billing_service',
'posthog.tasks.warehouse.validate_data_warehouse_table_columns',
+ 'posthog.tasks.wizard_blocklist.revoke_blocklisted_gateway_credentials',
])
# ---
diff --git a/posthog/tasks/test/test_wizard_blocklist.py b/posthog/tasks/test/test_wizard_blocklist.py
new file mode 100644
index 000000000000..4b733be5b95d
--- /dev/null
+++ b/posthog/tasks/test/test_wizard_blocklist.py
@@ -0,0 +1,222 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, revoke_oauth_session
+from posthog.models.user import User
+from posthog.tasks.wizard_blocklist import (
+ SweepResult,
+ revoke_blocklisted_gateway_credentials,
+ sweep_blocklisted_gateway_credentials,
+)
+
+
+class TestSweepBlocklistedGatewayCredentials(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = OAuthApplication.objects.create(
+ name="Wizard",
+ client_id="wizard_client_id",
+ client_secret="wizard_client_secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ user=self.user,
+ hash_client_secret=True,
+ algorithm="RS256",
+ )
+
+ def _token(
+ self,
+ *,
+ token: str,
+ scope: str = "llm_gateway:read",
+ expired: bool = False,
+ user: User | None = None,
+ scoped_organizations: list[str] | None = None,
+ ) -> OAuthAccessToken:
+ owner = user or self.user
+ expires = timezone.now() + (timedelta(hours=-1) if expired else timedelta(hours=1))
+ access_token = OAuthAccessToken.objects.create(
+ user=owner,
+ application=self.application,
+ token=token,
+ scope=scope,
+ expires=expires,
+ scoped_organizations=scoped_organizations,
+ )
+ OAuthRefreshToken.objects.create(
+ user=owner, application=self.application, token=f"refresh_{token}", access_token=access_token
+ )
+ return access_token
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_a_blocked_user_loses_the_access_and_refresh_token(self, mock_blocked: MagicMock) -> None:
+ self._token(token="live_token")
+
+ result = sweep_blocklisted_gateway_credentials()
+
+ assert (result.blocked_users, result.revoked_sessions) == (1, 1)
+ # Without the refresh token a ban only holds until the next refresh.
+ assert not OAuthAccessToken.objects.filter(application=self.application).exists()
+ assert not OAuthRefreshToken.objects.filter(application=self.application).exists()
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=False)
+ def test_an_unlisted_user_keeps_their_credentials(self, mock_blocked: MagicMock) -> None:
+ self._token(token="live_token")
+
+ assert sweep_blocklisted_gateway_credentials() == SweepResult()
+ assert OAuthAccessToken.objects.filter(application=self.application).exists()
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_a_wildcard_token_is_a_candidate(self, mock_blocked: MagicMock) -> None:
+ # The legacy gateway authenticates a bare `*`, so enumerating only the
+ # literal scope leaves it live.
+ self._token(token="wildcard_token", scope="*")
+
+ assert sweep_blocklisted_gateway_credentials() == SweepResult(blocked_users=1, revoked_sessions=1)
+ assert not OAuthAccessToken.objects.filter(token="wildcard_token").exists()
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_a_credential_without_the_gateway_scope_is_untouched(self, mock_blocked: MagicMock) -> None:
+ self._token(token="insight_token", scope="insight:read")
+
+ assert sweep_blocklisted_gateway_credentials() == SweepResult()
+ assert OAuthAccessToken.objects.filter(token="insight_token").exists()
+ # Nothing to revoke means nothing to ask about.
+ mock_blocked.assert_not_called()
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_an_expired_access_token_still_reaches_its_live_refresh_token(self, mock_blocked: MagicMock) -> None:
+ # 7-day access against a 30-day refresh token: selecting only live rows
+ # leaves a dormant account banned in name only.
+ self._token(token="expired_token", expired=True)
+
+ assert sweep_blocklisted_gateway_credentials() == SweepResult(blocked_users=1, revoked_sessions=1)
+ assert not OAuthRefreshToken.objects.filter(application=self.application).exists()
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_many_tokens_for_one_app_are_one_revoke_and_one_flag_read(self, mock_blocked: MagicMock) -> None:
+ self._token(token="token_one")
+ self._token(token="token_two")
+
+ # revoked_sessions is the length of the set the dedupe maintains, so it
+ # reads 1 whether or not the guard ran.
+ with patch("posthog.tasks.wizard_blocklist.revoke_oauth_session", wraps=revoke_oauth_session) as mock_revoke:
+ result = sweep_blocklisted_gateway_credentials()
+
+ assert (result.blocked_users, result.revoked_sessions) == (1, 1)
+ assert mock_revoke.call_count == 1
+ assert mock_blocked.call_count == 1
+ assert not OAuthAccessToken.objects.filter(application=self.application).exists()
+
+ @patch("posthog.tasks.wizard_blocklist._MAX_REVOCATIONS_PER_RUN", 1)
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_a_capped_run_says_so_instead_of_reporting_a_finished_estate(self, mock_blocked: MagicMock) -> None:
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ second_app = OAuthApplication.objects.create(
+ name="Wizard two",
+ client_id="wizard_client_id_two",
+ client_secret="wizard_client_secret_two",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ user=self.user,
+ hash_client_secret=True,
+ algorithm="RS256",
+ )
+ self._token(token="first_pair")
+ OAuthAccessToken.objects.create(
+ user=other,
+ application=second_app,
+ token="second_pair",
+ scope="llm_gateway:read",
+ expires=timezone.now() + timedelta(hours=1),
+ )
+
+ result = sweep_blocklisted_gateway_credentials()
+
+ assert result.capped is True
+ assert result.revoked_sessions == 1
+ # The backlog survives for the next tick.
+ assert OAuthAccessToken.objects.filter(token="second_pair").exists()
+
+ @patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=True)
+ def test_an_expired_token_with_no_refresh_token_is_not_a_candidate(self, mock_blocked: MagicMock) -> None:
+ # Sandbox tokens carry this scope, have no refresh token and are kept 30
+ # days, so reading them buys no reachability.
+ OAuthAccessToken.objects.create(
+ user=self.user,
+ application=self.application,
+ token="expired_no_refresh",
+ scope="llm_gateway:read",
+ expires=timezone.now() - timedelta(hours=1),
+ )
+
+ assert sweep_blocklisted_gateway_credentials() == SweepResult()
+ mock_blocked.assert_not_called()
+
+ def test_the_verdict_is_asked_per_organization_not_once_per_user(self) -> None:
+ # A user-keyed memo would answer for whichever row the scan read first.
+ self._token(token="org_a", scoped_organizations=["11111111-1111-4111-8111-111111111111"])
+ self._token(token="org_b", scoped_organizations=["22222222-2222-4222-8222-222222222222"])
+
+ with patch(
+ "posthog.tasks.wizard_blocklist.wizard_identity_blocked",
+ side_effect=lambda **kwargs: "22222222-2222-4222-8222-222222222222" in kwargs["organization_ids"],
+ ) as mock_blocked:
+ result = sweep_blocklisted_gateway_credentials()
+
+ assert mock_blocked.call_count == 2
+ assert result.blocked_users == 1
+
+ def test_a_credential_spanning_several_organizations_is_reached_by_a_ban_on_one(self) -> None:
+ # A first-party wizard grant is scoped to every organization its user
+ # belongs to, so a sole-organization reading would answer "" and miss.
+ self._token(
+ token="multi_org",
+ scoped_organizations=[
+ "11111111-1111-4111-8111-111111111111",
+ "22222222-2222-4222-8222-222222222222",
+ ],
+ )
+
+ with patch(
+ "posthog.tasks.wizard_blocklist.wizard_identity_blocked",
+ side_effect=lambda **kwargs: "22222222-2222-4222-8222-222222222222" in kwargs["organization_ids"],
+ ):
+ result = sweep_blocklisted_gateway_credentials()
+
+ assert result.revoked_sessions == 1
+ assert not OAuthAccessToken.objects.filter(token="multi_org").exists()
+
+ def test_only_the_blocked_user_loses_their_credentials(self) -> None:
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._token(token="blocked_token")
+ self._token(token="other_token", user=other)
+
+ with patch(
+ "posthog.tasks.wizard_blocklist.wizard_identity_blocked",
+ side_effect=lambda **kwargs: kwargs["distinct_id"] == str(self.user.distinct_id),
+ ):
+ result = sweep_blocklisted_gateway_credentials()
+
+ # A verdict cache keyed on anything but the user takes both or neither.
+ assert (result.blocked_users, result.revoked_sessions) == (1, 1)
+ assert not OAuthAccessToken.objects.filter(token="blocked_token").exists()
+ assert OAuthAccessToken.objects.filter(token="other_token").exists()
+
+ @patch("posthog.tasks.wizard_blocklist.record_blocklist_outcome")
+ @patch("posthog.tasks.wizard_blocklist.blocklist_flag_defined", return_value=False)
+ def test_a_run_with_no_flag_defined_reports_itself(self, mock_defined: MagicMock, mock_record: MagicMock) -> None:
+ # A lost definitions cache looks the same as no ban list, so the skipped
+ # run has to reach the counter.
+ self._token(token="untouched")
+
+ revoke_blocklisted_gateway_credentials()
+
+ mock_record.assert_called_once_with("revoke_sweep", "unconfigured")
+ assert OAuthAccessToken.objects.filter(token="untouched").exists()
diff --git a/posthog/tasks/wizard_blocklist.py b/posthog/tasks/wizard_blocklist.py
new file mode 100644
index 000000000000..e791741d1224
--- /dev/null
+++ b/posthog/tasks/wizard_blocklist.py
@@ -0,0 +1,143 @@
+"""Revoke the gateway credentials a blocklisted identity already holds.
+
+Consent refuses a banned user a new grant, but a ban still has to reach the
+credentials issued before it. This is what closes the legacy gateway, which
+authenticates the `pha_` straight out of Postgres and reads nothing else.
+
+Expired access tokens are candidates too: the row is how a still-live refresh
+token is reached, and refresh mints a replacement without passing consent.
+First-party access lasts 7 days against a 30-day refresh token, so selecting only
+live rows leaves a three-week window where a dormant account is invisible.
+"""
+
+import uuid
+
+from django.db.models import Q
+from django.utils import timezone
+
+import structlog
+from celery import shared_task
+
+from posthog.celery_queues import CeleryQueue
+from posthog.dataclasses import frozen
+from posthog.llm.wizard_blocklist import (
+ GATEWAY_BEARING_SCOPES,
+ blocklist_flag_defined,
+ record_blocklist_outcome,
+ wizard_identity_blocked,
+)
+from posthog.models.oauth import OAuthAccessToken, oauth_scope_tokens_expression, revoke_oauth_session
+from posthog.scoping_audit import skip_team_scope_audit
+
+logger = structlog.get_logger(__name__)
+
+_CHUNK_SIZE = 1000
+
+# One tick's ceiling. Each revocation is a locked transaction plus cascading
+# deletes, and a condition group with no properties matches every identity at
+# once; the next tick continues the backlog.
+_MAX_REVOCATIONS_PER_RUN = 200
+
+
+@frozen
+class SweepResult:
+ """What one sweep did. Named because two bare counts swap silently."""
+
+ blocked_users: int = 0
+ revoked_sessions: int = 0
+ capped: bool = False
+
+
+def sweep_blocklisted_gateway_credentials() -> SweepResult:
+ """Revoke every gateway-bearing session held by a blocklisted user."""
+ verdicts: dict[tuple[int, tuple[str, ...], tuple[int, ...]], bool] = {}
+ revoked_pairs: set[tuple[int, uuid.UUID]] = set()
+ blocked_user_ids: set[int] = set()
+
+ candidates = (
+ OAuthAccessToken.objects.alias(scope_tokens=oauth_scope_tokens_expression())
+ .filter(scope_tokens__overlap=sorted(GATEWAY_BEARING_SCOPES), application_id__isnull=False)
+ .filter(user__isnull=False)
+ # An expired row is only worth reading for the refresh token hanging off it.
+ # Server-minted sandbox tokens carry this scope, expire in hours, have no
+ # refresh token and are kept 30 days, so admitting every expired row scans
+ # that backlog for credentials a ban cannot reach.
+ .filter(Q(expires__gt=timezone.now()) | Q(refresh_token__isnull=False))
+ .select_related("user", "application")
+ .iterator(chunk_size=_CHUNK_SIZE)
+ )
+ for token in candidates:
+ user = token.user
+ if user is None or token.application_id is None:
+ continue
+ # Keyed on the whole question: the verdict depends on the token's own
+ # organizations and teams, so a user-keyed memo would answer for whichever
+ # row the unordered scan read first.
+ question = (user.pk, _organization_ids(token), _team_ids(token))
+ blocked = verdicts.get(question)
+ if blocked is None:
+ blocked = wizard_identity_blocked(
+ distinct_id=str(user.distinct_id),
+ email=user.email,
+ surface="revoke_sweep",
+ user_uuid=str(user.uuid),
+ organization_ids=question[1],
+ team_ids=question[2],
+ )
+ verdicts[question] = blocked
+ if blocked:
+ blocked_user_ids.add(user.pk)
+ if not blocked:
+ continue
+ # revoke_oauth_session sweeps the whole (user, application) pair, so a user
+ # holding several tokens against one app is one revoke, not one per token.
+ pair = (user.pk, token.application_id)
+ if pair in revoked_pairs:
+ continue
+ revoke_oauth_session(access_token=token)
+ revoked_pairs.add(pair)
+ if len(revoked_pairs) >= _MAX_REVOCATIONS_PER_RUN:
+ logger.warning(
+ "wizard_blocklist: revocation cap reached, deferring the rest to the next run",
+ revoked_sessions=len(revoked_pairs),
+ )
+ # A capped run has not swept the estate; the counts alone would read
+ # as one that had.
+ return SweepResult(blocked_users=len(blocked_user_ids), revoked_sessions=len(revoked_pairs), capped=True)
+
+ return SweepResult(blocked_users=len(blocked_user_ids), revoked_sessions=len(revoked_pairs))
+
+
+def _organization_ids(token: OAuthAccessToken) -> tuple[str, ...]:
+ """Every organization this credential is scoped to. Not the user's current
+ organization, which is writable through `PATCH /api/users/@me/` and would let a
+ banned account switch itself out of the match.
+
+ All of them rather than the sole one: a first-party wizard grant is scoped to
+ every organization its user belongs to, so a single-valued reading would leave
+ an organization ban unenforceable for anyone in more than one.
+ """
+ return tuple(str(organization_id) for organization_id in (token.scoped_organizations or []))
+
+
+def _team_ids(token: OAuthAccessToken) -> tuple[int, ...]:
+ return tuple(token.scoped_teams or [])
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+@skip_team_scope_audit
+def revoke_blocklisted_gateway_credentials() -> None:
+ if not blocklist_flag_defined():
+ # Also true when the SDK lost its definitions: a 401, a quota limit or a
+ # missing personal API key all reset them to empty. Recorded so a sweep
+ # that checked nothing is not silence.
+ record_blocklist_outcome("revoke_sweep", "unconfigured")
+ logger.info("wizard_blocklist: no blocklist flag defined, skipping the sweep")
+ return
+ result = sweep_blocklisted_gateway_credentials()
+ logger.info(
+ "wizard_blocklist: sweep complete",
+ blocked_users=result.blocked_users,
+ revoked_sessions=result.revoked_sessions,
+ capped=result.capped,
+ )
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index de8222553bd1..7194ec123016 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -8,7 +8,9 @@ from django.utils import timezone
import structlog
+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blocked
from posthog.models import OAuthAccessToken, OAuthApplication
+from posthog.models.team.team import Team
from posthog.models.utils import generate_random_oauth_access_token
from posthog.scopes import (
API_SCOPE_OBJECTS,
@@ -542,12 +544,38 @@ def get_wizard_app() -> OAuthApplication:
)
+def _organization_id_for_team(team_id: int) -> str:
+ """The organization the run is pinned to. Not the user's current one, which is
+ writable through `PATCH /api/users/@me/` and so cannot carry a ban."""
+ organization_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()
+ return str(organization_id) if organization_id else ""
+
+
+class WizardIdentityBlockedError(Exception):
+ """The abuse blocklist refuses this identity a wizard credential. Distinct from
+ the mint's RuntimeError cases because it is permanent, and a caller that retries
+ a transient token failure must not retry this one."""
+
+
def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:
"""Mint an OAuth access token under the wizard's own app for a cloud wizard run.
Deliberately separate from the sandbox/agent token (`create_oauth_access_token_for_user`) so the
wizard's scopes stay independent of the agent's. Uses the wizard app's configured scope ceiling.
+
+ Gated here rather than only at the HTTP kickoff, which a workflow retry or
+ resume reaches with no request in front of it.
"""
+ if wizard_identity_blocked(
+ distinct_id=str(user.distinct_id),
+ email=user.email,
+ surface="wizard_mint",
+ user_uuid=str(user.uuid),
+ organization_ids=[_organization_id_for_team(team_id)],
+ team_ids=[team_id],
+ ):
+ raise WizardIdentityBlockedError(WIZARD_BLOCKED_DETAIL)
+
app = get_wizard_app()
ceiling = resolve_ceiling(app.ceiling_scopes)
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index 1a59c6e34a78..8c429776a91c 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -3,6 +3,9 @@ from pathlib import Path
from typing import cast
from uuid import uuid4
+import pytest
+from unittest.mock import patch
+
from django.test import SimpleTestCase, TestCase, override_settings
from parameterized import parameterized
@@ -24,6 +27,7 @@ from posthog.temporal.oauth import (
McpScopePreset,
ScoutScopePosture,
ScoutScopePreset,
+ WizardIdentityBlockedError,
create_oauth_access_token_for_user,
create_wizard_oauth_access_token_for_user,
has_write_scopes,
@@ -367,6 +371,19 @@ class TestCreateWizardOAuthAccessTokenForUser(TestCase):
user = User.objects.create(email="[email protected]")
return user, team
+ @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)
+ @patch("posthog.temporal.oauth.wizard_identity_blocked", return_value=True)
+ def test_a_blocklisted_identity_is_refused_a_wizard_token(self, mock_blocked) -> None:
+ # Gated at the mint, not only at the HTTP kickoff: a workflow retry or resume
+ # reaches here with no request in front of it.
+ self._create_wizard_app(scopes=["project:read", "llm_gateway:read"])
+ user, team = self._create_user_and_team()
+
+ with pytest.raises(WizardIdentityBlockedError):
+ create_wizard_oauth_access_token_for_user(user, team.id)
+
+ assert not OAuthAccessToken.objects.exists()
+
@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)
def test_mints_token_under_wizard_app_with_its_scopes(self) -> None:
# The token must be minted under the wizard's own app (so the gateway authorizes it like a normal wizard run)
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 9f709af939a2..293e1c2f9ae1 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -13,6 +13,7 @@ from posthog.temporal.oauth import (
PosthogMcpScopes,
SandboxOAuthApplication,
ScoutScopePosture,
+ WizardIdentityBlockedError,
create_oauth_access_token_for_user as _create_oauth_access_token_for_user,
create_wizard_oauth_access_token_for_user as _create_wizard_oauth_access_token_for_user,
resolve_scopes,
@@ -255,6 +256,10 @@ def create_wizard_oauth_access_token(task: Task) -> str:
try:
return _create_wizard_oauth_access_token_for_user(task.created_by, task.team_id)
+ except WizardIdentityBlockedError as err:
+ # Fatal: the ban holds until someone edits the flag, so retrying only burns
+ # attempts against a settled answer.
+ raise TaskInvalidStateError(str(err), {"team_id": task.team_id}, cause=err) from err
except RuntimeError as err:
raise OAuthTokenError(str(err), {"team_id": task.team_id}, cause=err) from err