: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(security): let block rules refuse signup and AI gateway requests (#110812)
Yasen533fc4a86df7
diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.pyindex a210c7153598..ccc1c6d5f474 100644--- a/ee/api/agentic_provisioning/accounts.py+++ b/ee/api/agentic_provisioning/accounts.py@@ -12,6 +12,7 @@ from django.db import IntegrityErrorfrom django.utils import timezonefrom posthog.api.authentication import password_reset_token_generator+from posthog.api.signup import SIGNUP_BLOCKED_DETAIL, signup_refusedfrom posthog.event_usage import report_user_signed_upfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import EmailLookupHandler@@ -22,6 +23,8 @@ from posthog.models.user import Userfrom posthog.scopes import scopes_within_ceilingfrom posthog.tasks.email import send_provisioning_welcome+from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODE+from ee.api.agentic_provisioning.analytics import capture_provisioning_eventfrom ee.api.agentic_provisioning.constants import (AUTH_CODE_CACHE_PREFIX,@@ -234,6 +237,10 @@ def handle_new_user(label = partner_label(partner)org_name = configuration.get("organization_name") or f"{label} ({email})"+ if signup_refused(email, call_site="agentic_provisioning"):+ capture_provisioning_event("account_request", "access_blocked", partner=partner, region=region)+ raise ProvisioningError(SECURITY_REFUSAL_CODE, SIGNUP_BLOCKED_DETAIL, request_id=request_id, status=403)+try:organization, team, user = User.objects.bootstrap(organization_name=org_name,diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex 9ce946566903..b8223b7d4f2f 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -54,6 +54,13 @@ class TestAccountRequests(ProvisioningTestBase):assert len(data["oauth"]["code"]) > 0assert User.objects.filter(email="[email protected]").exists()+ def test_new_user_refused_by_an_access_rule_gets_no_account(self):+ with patch("ee.api.agentic_provisioning.accounts.signup_refused", return_value=True):+ res = self._post_account_request(self._account_request_payload())+ assert res.status_code == 403+ assert res.json()["error"]["code"] == "access_blocked"+ assert not User.objects.filter(email="[email protected]").exists()+def test_new_user_creates_org_and_team_attributed_to_partner(self):self._post_account_request(self._account_request_payload())user = User.objects.get(email="[email protected]")diff --git a/ee/partners/stripe/api/provisioning/core.py b/ee/partners/stripe/api/provisioning/core.pyindex 703d0ba9e28e..180823aa1b58 100644--- a/ee/partners/stripe/api/provisioning/core.py+++ b/ee/partners/stripe/api/provisioning/core.py@@ -257,6 +257,8 @@ def handle_new_user(# (500) where the spec calls for a 400 invalid_request.org_name = configuration.get("organization_name") or f"{PARTNER_LABEL} ({email})"+ # The signup access rules do not apply here. Stripe's provisioning spec defines no refusal for a new+ # account, and Stripe keeps a valid card on file for every account it provisions.try:organization, team, user = User.objects.bootstrap(organization_name=org_name,diff --git a/ee/vercel/integration.py b/ee/vercel/integration.pyindex 987bca1147d9..976a7422e4aa 100644--- a/ee/vercel/integration.py+++ b/ee/vercel/integration.py@@ -17,6 +17,7 @@ import structlogfrom rest_framework import exceptionsfrom two_factor.utils import default_device+from posthog.api.signup import SIGNUP_BLOCKED_DETAIL, signup_refusedfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.dataclasses import frozenfrom posthog.event_usage import report_user_signed_up@@ -35,6 +36,7 @@ from posthog.utils import absolute_urifrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODEfrom ee.api.authentication import VercelAuthenticationfrom ee.api.vercel.types import VercelClaims, VercelUserClaims@@ -1145,6 +1147,9 @@ class VercelIntegration:elif email:first_name = email.split("@")[0]+ if signup_refused(email, call_site="vercel_provisioning"):+ raise exceptions.PermissionDenied(SIGNUP_BLOCKED_DETAIL, code=SECURITY_REFUSAL_CODE)+user = User.objects.create_user(email=email,password=None,diff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.pyindex 45d72680cf1b..e46b1a57e7e2 100644--- a/ee/vercel/test/test_integration.py+++ b/ee/vercel/test/test_integration.py@@ -1,6 +1,7 @@from typing import Anyfrom urllib.parse import parse_qs, urlparse+import pytestfrom unittest import mockfrom unittest.mock import Mock, patch@@ -778,6 +779,19 @@ class TestVercelIntegration(TestCase):new_user = User.objects.get(email=payload_without_name["account"]["contact"]["email"])assert new_user.first_name == payload_without_name["account"]["contact"]["email"].split("@")[0]+ @patch("ee.vercel.integration.signup_refused", return_value=True)+ @patch("ee.vercel.integration.report_user_signed_up")+ def test_upsert_installation_refused_by_an_access_rule_creates_no_user(self, mock_report, _refused):+ new_user_claims = self._create_user_claims("refused_user_789")+ new_user_claims.installation_id = self.NEW_INSTALLATION_ID+ new_user_claims.sub = "account:test:user:refused"++ with pytest.raises(exceptions.PermissionDenied) as raised:+ VercelIntegration.upsert_installation(self.NEW_INSTALLATION_ID, self.payload, new_user_claims)++ assert raised.value.get_codes() == "access_blocked"+ assert not User.objects.filter(email=self.payload["account"]["contact"]["email"]).exists()+@patch("ee.vercel.integration.report_user_signed_up")def test_upsert_installation_does_not_reactivate_inactive_user(self, mock_report):new_installation_id = self.NEW_INSTALLATION_IDdiff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex a11b1f0ce695..f845fe735fb8 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -38,6 +38,7 @@ from posthog.helpers.oauth_pending_connection import (PENDING_OAUTH_CONNECTION_MAX_AGE_SECONDS,PendingOAuthConnection,)+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAILfrom posthog.models.oauth import (OAuthAccessToken,OAuthApplication,@@ -3500,20 +3501,34 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(mock_blocked.call_args.kwargs["surface"], "oauth_authorize")self.assertEqual(mock_blocked.call_args.kwargs["email"], self.user.email)- @patch("posthog.api.oauth.views.security_shadow_check")- def test_authorize_records_a_shadow_access_check_for_the_gateway_scope(self, shadow: MagicMock) -> None:+ @patch("posthog.api.oauth.views.security_access_refused", return_value=False)+ def test_authorize_asks_the_access_rules_for_the_gateway_scope(self, check: MagicMock) -> None:app = self._create_first_party_app_with_ceiling("insight:read", "llm_gateway:read")self._first_party_authorize_grant(app, "insight:read llm_gateway:read")- shadow.assert_called_once()- subject, surface = shadow.call_args.args+ check.assert_called_once()+ subject, surface = check.call_args.argsself.assertEqual(surface, SecuritySurface.AI_GATEWAY)self.assertEqual(subject.user_uuid, str(self.user.uuid))- self.assertEqual(shadow.call_args.kwargs, {"call_site": "oauth_authorize"})+ self.assertEqual(check.call_args.kwargs, {"call_site": "oauth_authorize"})++ @patch("posthog.api.oauth.views.wizard_identity_blocked", return_value=False)+ @patch("posthog.api.oauth.views.security_access_refused", return_value=True)+ def test_authorize_refuses_the_gateway_scope_when_an_access_rule_refuses(+ self, check: MagicMock, mock_blocked: MagicMock+ ) -> None:+ 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_description"], WIZARD_BLOCKED_DETAIL)+ self.assertFalse(OAuthGrant.objects.filter(application=app).exists())- @patch("posthog.api.oauth.views.security_shadow_check", side_effect=RuntimeError("boom"))- def test_authorize_grants_the_gateway_scope_when_the_shadow_check_raises(self, shadow: MagicMock) -> None:+ @patch("posthog.api.oauth.views.security_access_refused", side_effect=RuntimeError("boom"))+ def test_authorize_grants_the_gateway_scope_when_the_access_check_raises(self, shadow: MagicMock) -> None: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")diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 4a2b2acbce1e..6f1a1fa6f8e6 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -103,7 +103,7 @@ from posthog.utils import absolute_uri, get_instance_region, get_trusted_client_from posthog.views import login_requiredfrom products.access_control.backend.facade.api import user_organizations_use_access_controls-from products.security.backend.facade.api import shadow_check as security_shadow_check+from products.security.backend.facade.api import access_refused as security_access_refusedfrom products.security.backend.facade.contracts import SubjectInput as SecuritySubjectfrom products.security.backend.facade.enums import Surface as SecuritySurface@@ -352,7 +352,7 @@ def _gateway_blocklist_block(return Noneorganization_ids = _scoped_organization_ids(request.user, access_level, scoped_organization_ids, scoped_team_ids)try:- security_shadow_check(+ refused = security_access_refused(SecuritySubject(email=request.user.email,user_uuid=str(request.user.uuid),@@ -363,8 +363,9 @@ def _gateway_blocklist_block(call_site="oauth_authorize",)except Exception:- logger.exception("security_shadow_check_site_failed", call_site="oauth_authorize")- if not wizard_identity_blocked(+ logger.exception("security_access_check_site_failed", call_site="oauth_authorize")+ refused = False+ if not refused and not wizard_identity_blocked(distinct_id=str(request.user.distinct_id),email=request.user.email,surface="oauth_authorize",diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 9d9ab5a4c28a..e3412767c3d4 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -18,6 +18,8 @@ import structlogimport posthoganalyticsfrom rest_framework import exceptions, generics, permissions, response, serializers, statusfrom rest_framework.request import Request+from social_core.backends.base import BaseAuth+from social_core.exceptions import AuthFailedfrom social_core.pipeline.partial import partialfrom social_django.strategy import DjangoStrategyfrom webauthn.helpers import base64url_to_bytes@@ -46,12 +48,22 @@ from posthog.workos_radar import RadarAction, RadarAuthMethod, evaluate_auth_attfrom products.demo.backend.facade.api import HedgeboxMatrix, MatrixManagerfrom products.growth.backend.temporal.signup_enrichment.trigger import start_signup_enrichment_workflow-from products.security.backend.facade.api import shadow_check as security_shadow_check+from products.security.backend.facade.api import (+ REFUSAL_CODE as SECURITY_REFUSAL_CODE,+ access_refused as security_access_refused,+)from products.security.backend.facade.contracts import SubjectInput as SecuritySubjectfrom products.security.backend.facade.enums import Surface as SecuritySurfacelogger = structlog.get_logger(__name__)+# Says nothing about the rule that matched, so an abuser learns nothing from it. The code+# is what lets support trace the refusal to an access rule.+SIGNUP_BLOCKED_DETAIL = (+ "We couldn't complete your signup. If you think this is a mistake, contact support "+ f"and quote the code {SECURITY_REFUSAL_CODE}."+)+def _save_session_with_recovery(session: SessionBase) -> None:"""Persist session state and recover from missing-row session races."""@@ -238,7 +250,7 @@ class SignupSerializer(serializers.Serializer):)try:- security_shadow_check(+ refused = security_access_refused(SecuritySubject(email=validated_data["email"],ip=get_trusted_client_ip(getattr(request, "_request", request)),@@ -247,7 +259,10 @@ class SignupSerializer(serializers.Serializer):call_site="signup",)except Exception:- logger.exception("security_shadow_check_site_failed", call_site="signup")+ logger.exception("security_access_check_site_failed", call_site="signup")+ refused = False+ if refused:+ raise exceptions.PermissionDenied(SIGNUP_BLOCKED_DETAIL, code=SECURITY_REFUSAL_CODE)is_instance_first_user: bool = not User.objects.exists()@@ -601,7 +616,7 @@ class InviteSignupSerializer(serializers.Serializer):# Runs for both branches below: an already signed-in user accepting an invite never hits# the "not user" branch, so this must not live inside it.try:- security_shadow_check(+ refused = security_access_refused(SecuritySubject(email=(user.email if user else invite.target_email) or "",user_uuid=str(user.uuid) if user else None,@@ -611,7 +626,10 @@ class InviteSignupSerializer(serializers.Serializer):call_site="invite_signup",)except Exception:- logger.exception("security_shadow_check_site_failed", call_site="invite_signup")+ logger.exception("security_access_check_site_failed", call_site="invite_signup")+ refused = False+ if refused:+ raise exceptions.PermissionDenied(SIGNUP_BLOCKED_DETAIL, code=SECURITY_REFUSAL_CODE)with transaction.atomic():if not user:@@ -874,8 +892,49 @@ def lookup_invite_for_saml(email: str, saml_relay_state: str) -> Optional[Organi)+def signup_refused(email: str, *, call_site: str) -> bool:+ """Whether an enforced signup rule refuses a new account for this email. Never raises.++ For signup paths that a partner's server drives, so there is no person's IP to check.+ """+ try:+ return security_access_refused(SecuritySubject(email=email), SecuritySurface.SIGNUP, call_site=call_site)+ except Exception:+ logger.exception("security_access_check_site_failed", call_site=call_site)+ return False+++def _refuse_blocked_sso_join(strategy: DjangoStrategy, backend: BaseAuth, email: str, user: Optional[User]) -> None:+ """Refuse an SSO signup or organization join that an enforced signup rule blocks.++ Invite and verified-domain joins over SSO never reach the signup serializers, so they run this+ check themselves, right before an account is created or joins an organization.+ """+ try:+ refused = security_access_refused(+ SecuritySubject(+ email=(user.email if user else email) or "",+ user_uuid=str(user.uuid) if user else None,+ ip=get_trusted_client_ip(strategy.request),+ ),+ SecuritySurface.SIGNUP,+ call_site="sso_signup",+ )+ except Exception:+ logger.exception("security_access_check_site_failed", call_site="sso_signup")+ refused = False+ if refused:+ raise AuthFailed(backend, SIGNUP_BLOCKED_DETAIL)++def process_social_invite_signup(- strategy: DjangoStrategy, invite_id: str, email: str, full_name: str, user: Optional[User] = None+ strategy: DjangoStrategy,+ invite_id: str,+ email: str,+ full_name: str,+ user: Optional[User] = None,+ *,+ backend: BaseAuth,) -> Optional[User]:try:# nosemgrep: idor-lookup-without-org (invite UUID from server session serves as auth token)@@ -892,6 +951,8 @@ def process_social_invite_signup(if OrganizationDomain.objects.is_email_blocked_by_domain_enforcement(email, invite.organization):return None+ _refuse_blocked_sso_join(strategy, backend, email, user)+# Capture before invite.use() — use() deletes the invite row, so the in-memory boolean is# the only safe source of truth for delegation routing.is_delegation = bool(getattr(invite, "is_setup_delegation", False))@@ -918,7 +979,7 @@ def process_social_invite_signup(def process_social_domain_jit_provisioning_signup(- strategy: DjangoStrategy, email: str, full_name: str, user: Optional[User] = None+ strategy: DjangoStrategy, email: str, full_name: str, user: Optional[User] = None, *, backend: BaseAuth) -> Optional[User]:# Check if the user is on an allowed domaindomain = email.split("@")[-1]@@ -943,6 +1004,8 @@ def process_social_domain_jit_provisioning_signup(scim_enabled=scim_enabled,)if domain_instance.is_verified and domain_instance.jit_provisioning_enabled:+ if not user or not user.organizations.filter(pk=domain_instance.organization_id).exists():+ _refuse_blocked_sso_join(strategy, backend, email, user)if not user:try:invite: OrganizationInvite = OrganizationInvite.objects.get(@@ -1068,9 +1131,9 @@ def social_create_user(user.save()if invite_id:- process_social_invite_signup(strategy, invite_id, user.email, user.first_name, user)+ process_social_invite_signup(strategy, invite_id, user.email, user.first_name, user, backend=backend)else:- process_social_domain_jit_provisioning_signup(strategy, user.email, user.first_name, user)+ process_social_domain_jit_provisioning_signup(strategy, user.email, user.first_name, user, backend=backend)return {"is_new": False}@@ -1094,13 +1157,13 @@ def social_create_user(if invite_id:from_invite = True- user = process_social_invite_signup(strategy, invite_id, email, full_name)+ user = process_social_invite_signup(strategy, invite_id, email, full_name, backend=backend)if user is None:return redirect("/login?error_code=invalid_invite")else:# JIT Provisioning?- user = process_social_domain_jit_provisioning_signup(strategy, email, full_name)+ user = process_social_domain_jit_provisioning_signup(strategy, email, full_name, backend=backend)logger.info(f"social_create_user_jit_user",full_name_len=len(full_name),diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 8072e643ac26..aab4a926217d 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -3182,7 +3182,9 @@ class TestInviteSignupAPI(APIBaseTest):def test_process_social_invite_signup_returns_none_for_nonexistent_invite(self):nonexistent_id = str(uuid.uuid4())- result = process_social_invite_signup(mock.MagicMock(), nonexistent_id, "[email protected]", "Test User")+ result = process_social_invite_signup(+ mock.MagicMock(), nonexistent_id, "[email protected]", "Test User", backend=mock.MagicMock()+ )self.assertIsNone(result)@pytest.mark.skip_on_multitenancydiff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 95b0658e37aa..e75a5a58f5cb 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -48,7 +48,7 @@ from posthog.storage.gateway_credential_cache import (from posthog.user_permissions import UserPermissionsfrom posthog.utils import get_trusted_client_ip-from products.security.backend.facade.api import shadow_check as security_shadow_check+from products.security.backend.facade.api import access_refused as security_access_refusedfrom products.security.backend.facade.contracts import SubjectInput as SecuritySubjectfrom products.security.backend.facade.enums import Surface as SecuritySurfacefrom products.tasks.backend.facade import api as tasks_facade@@ -259,7 +259,7 @@ class SetupWizardViewSet(viewsets.ViewSet):refuse("blocked", exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL), user=user)try:- security_shadow_check(+ refused = security_access_refused(SecuritySubject(email=user.email,user_uuid=str(user.uuid),@@ -270,7 +270,11 @@ class SetupWizardViewSet(viewsets.ViewSet):call_site="wizard_gateway_token",)except Exception:- logger.exception("security_shadow_check_site_failed", call_site="wizard_gateway_token")+ logger.exception("security_access_check_site_failed", call_site="wizard_gateway_token")+ refused = False+ if refused:+ # The flag's refusal, word for word, so a client cannot tell which blocklist matched.+ refuse("blocked", exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL), user=user)# A kill switch, not a rollout gate: only a literal False refuses. With the# legacy product off there is no second path, so reading an outage as "not@@ -443,7 +447,7 @@ class SetupWizardViewSet(viewsets.ViewSet):raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)try:- security_shadow_check(+ refused = security_access_refused(SecuritySubject(email=user.email,user_uuid=str(user.uuid),@@ -454,7 +458,10 @@ class SetupWizardViewSet(viewsets.ViewSet):call_site="wizard_cloud_run",)except Exception:- logger.exception("security_shadow_check_site_failed", call_site="wizard_cloud_run")+ logger.exception("security_access_check_site_failed", call_site="wizard_cloud_run")+ refused = False+ if refused:+ raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)self._reserve_cloud_run_attempt(user.id)diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 1faa1e4add34..27bfb28d114f 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -10,6 +10,7 @@ from django.core.cache import cachefrom django.test import override_settingsfrom django.utils import timezone+from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom rest_framework import statusfrom rest_framework.exceptions import AuthenticationFailed, Throttled@@ -76,9 +77,13 @@ class SetupWizardCloudRunTests(APIBaseTest):assert kwargs["branch"] is Noneassert kwargs["team"].id == self.team.id- @patch("posthog.api.wizard.http.security_shadow_check")+ @parameterized.expand([("allowed", False, status.HTTP_200_OK), ("refused", True, status.HTTP_403_FORBIDDEN)])+ @patch("posthog.api.wizard.http.security_access_refused")@patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")- def test_cloud_run_records_a_shadow_access_check(self, mock_create, shadow: MagicMock) -> None:+ def test_cloud_run_asks_the_access_rules(+ self, _name: str, refused: bool, expected_status: int, mock_create, check: MagicMock+ ) -> None:+ check.return_value = refusedmock_create.return_value = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))response = self.client.post(@@ -87,12 +92,15 @@ class SetupWizardCloudRunTests(APIBaseTest):format="json",)- assert response.status_code == status.HTTP_200_OK, response.content- shadow.assert_called_once()- subject, surface = shadow.call_args.args+ assert response.status_code == expected_status, response.content+ check.assert_called_once()+ subject, surface = check.call_args.argsassert surface == SecuritySurface.AI_GATEWAYassert subject.organization_ids == (str(self.team.organization_id),)- assert shadow.call_args.kwargs == {"call_site": "wizard_cloud_run"}+ assert check.call_args.kwargs == {"call_site": "wizard_cloud_run"}+ assert mock_create.called is not refused+ if refused:+ assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL@patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")def test_rejects_invalid_repository_format(self, mock_create):@@ -308,26 +316,39 @@ class SetupWizardGatewayTokenTests(APIBaseTest):"posture": "new",}- @patch("posthog.api.wizard.http.security_shadow_check")+ @parameterized.expand([("allowed", False, status.HTTP_201_CREATED), ("refused", True, status.HTTP_403_FORBIDDEN)])+ @patch("posthog.api.wizard.http.security_access_refused")@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_gateway_token_records_a_shadow_access_check(- self, mock_authentication, mock_flag, mock_mint, mock_authorized, shadow: MagicMock+ def test_gateway_token_asks_the_access_rules(+ self,+ _name: str,+ refused: bool,+ expected_status: int,+ mock_authentication,+ mock_flag,+ mock_mint,+ mock_authorized,+ check: MagicMock,) -> None:+ check.return_value = refusedself._mock_oauth(mock_authentication)response = self.client.post(self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"})- assert response.status_code == status.HTTP_201_CREATED, response.content- shadow.assert_called_once()- subject, surface = shadow.call_args.args+ assert response.status_code == expected_status, response.content+ check.assert_called_once()+ subject, surface = check.call_args.argsassert surface == SecuritySurface.AI_GATEWAYassert subject.organization_ids == (str(self.team.organization_id),)- assert shadow.call_args.kwargs == {"call_site": "wizard_gateway_token"}+ assert check.call_args.kwargs == {"call_site": "wizard_gateway_token"}+ assert mock_mint.called is not refused+ if refused:+ assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL@override_settings(DEBUG=False, WIZARD_GATEWAY_TIERS={"new": {"mints_per_week": 2}})@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)diff --git a/posthog/tasks/test/test_wizard_blocklist.py b/posthog/tasks/test/test_wizard_blocklist.pyindex 4b733be5b95d..a54f01bba869 100644--- a/posthog/tasks/test/test_wizard_blocklist.py+++ b/posthog/tasks/test/test_wizard_blocklist.py@@ -5,6 +5,8 @@ from unittest.mock import MagicMock, patchfrom django.utils import timezone+from parameterized import parameterized+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, revoke_oauth_sessionfrom posthog.models.user import Userfrom posthog.tasks.wizard_blocklist import (@@ -37,6 +39,7 @@ class TestSweepBlocklistedGatewayCredentials(APIBaseTest):expired: bool = False,user: User | None = None,scoped_organizations: list[str] | None = None,+ scoped_teams: list[int] | None = None,) -> OAuthAccessToken:owner = user or self.userexpires = timezone.now() + (timedelta(hours=-1) if expired else timedelta(hours=1))@@ -47,17 +50,23 @@ class TestSweepBlocklistedGatewayCredentials(APIBaseTest):scope=scope,expires=expires,scoped_organizations=scoped_organizations,+ scoped_teams=scoped_teams,)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:+ @parameterized.expand([("banned by the flag", True, False), ("banned by an access rule", False, True)])+ def test_a_blocked_user_loses_the_access_and_refresh_token(self, _name: str, flag: bool, rule: bool) -> None:self._token(token="live_token")- result = sweep_blocklisted_gateway_credentials()+ with (+ patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=flag),+ patch("posthog.tasks.wizard_blocklist.security_is_enforced", return_value=rule),+ patch("posthog.tasks.wizard_blocklist.security_gateway_credentials_revoked", return_value=rule),+ ):+ 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.@@ -209,14 +218,38 @@ class TestSweepBlocklistedGatewayCredentials(APIBaseTest):assert not OAuthAccessToken.objects.filter(token="blocked_token").exists()assert OAuthAccessToken.objects.filter(token="other_token").exists()+ def test_an_organization_rule_reaches_a_token_scoped_only_to_one_of_its_teams(self) -> None:+ # A team-scoped token carries no organizations of its own, and rules have no team target.+ self._token(token="team_token", scoped_teams=[self.team.id])++ with (+ patch("posthog.tasks.wizard_blocklist.wizard_identity_blocked", return_value=False),+ patch("posthog.tasks.wizard_blocklist.security_is_enforced", return_value=True),+ patch("posthog.tasks.wizard_blocklist.security_gateway_credentials_revoked", return_value=False) as rule,+ ):+ sweep_blocklisted_gateway_credentials()++ assert rule.call_args.args[0].organization_ids == (str(self.team.organization_id),)++ @parameterized.expand([("gateway in shadow", False, True), ("gateway enforced", True, False)])+ @patch("posthog.tasks.wizard_blocklist.security_gateway_credentials_revoked", return_value=True)@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:+ def test_a_run_with_no_flag_defined_reports_itself(+ self,+ _name: str,+ enforced: bool,+ kept: bool,+ mock_defined: MagicMock,+ mock_record: MagicMock,+ _rule: MagicMock,+ ) -> None:# A lost definitions cache looks the same as no ban list, so the skipped- # run has to reach the counter.+ # run has to reach the counter. Enforced access rules still need the sweep.self._token(token="untouched")- revoke_blocklisted_gateway_credentials()+ with patch("posthog.tasks.wizard_blocklist.security_is_enforced", return_value=enforced):+ revoke_blocklisted_gateway_credentials()- mock_record.assert_called_once_with("revoke_sweep", "unconfigured")- assert OAuthAccessToken.objects.filter(token="untouched").exists()+ mock_record.assert_any_call("revoke_sweep", "unconfigured")+ assert OAuthAccessToken.objects.filter(token="untouched").exists() is keptdiff --git a/posthog/tasks/wizard_blocklist.py b/posthog/tasks/wizard_blocklist.pyindex e791741d1224..1f95fe4462d2 100644--- a/posthog/tasks/wizard_blocklist.py+++ b/posthog/tasks/wizard_blocklist.py@@ -1,5 +1,8 @@"""Revoke the gateway credentials a blocklisted identity already holds.+An identity is blocklisted when the wizard blocklist flag names it, or when an access rule+refuses it while the AI gateway is enforced.+Consent refuses a banned user a new grant, but a ban still has to reach thecredentials issued before it. This is what closes the legacy gateway, whichauthenticates the `pha_` straight out of Postgres and reads nothing else.@@ -27,8 +30,16 @@ from posthog.llm.wizard_blocklist import (wizard_identity_blocked,)from posthog.models.oauth import OAuthAccessToken, oauth_scope_tokens_expression, revoke_oauth_session+from posthog.models.team import Teamfrom posthog.scoping_audit import skip_team_scope_audit+from products.security.backend.facade.api import (+ gateway_credentials_revoked as security_gateway_credentials_revoked,+ is_enforced as security_is_enforced,+)+from products.security.backend.facade.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurface+logger = structlog.get_logger(__name__)_CHUNK_SIZE = 1000@@ -53,6 +64,7 @@ def sweep_blocklisted_gateway_credentials() -> SweepResult:verdicts: dict[tuple[int, tuple[str, ...], tuple[int, ...]], bool] = {}revoked_pairs: set[tuple[int, uuid.UUID]] = set()blocked_user_ids: set[int] = set()+ team_organizations: dict[int, str] = {}candidates = (OAuthAccessToken.objects.alias(scope_tokens=oauth_scope_tokens_expression())@@ -83,6 +95,15 @@ def sweep_blocklisted_gateway_credentials() -> SweepResult:user_uuid=str(user.uuid),organization_ids=question[1],team_ids=question[2],+ ) or (+ security_is_enforced(SecuritySurface.AI_GATEWAY)+ and security_gateway_credentials_revoked(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ organization_ids=_rule_organization_ids(question[1], question[2], team_organizations),+ )+ ))verdicts[question] = blockedif blocked:@@ -124,6 +145,23 @@ def _team_ids(token: OAuthAccessToken) -> tuple[int, ...]:return tuple(token.scoped_teams or [])+def _rule_organization_ids(+ organization_ids: tuple[str, ...], team_ids: tuple[int, ...], team_organizations: dict[int, str]+) -> tuple[str, ...]:+ """The credential's organizations plus the ones that own its teams.++ Access rules have no team target, and a team-scoped credential carries no organizations of+ its own, so an organization rule reaches it only through its teams. `team_organizations`+ caches the lookup across one sweep.+ """+ missing = [team_id for team_id in team_ids if team_id not in team_organizations]+ if missing:+ for team_id, organization_id in Team.objects.filter(id__in=missing).values_list("id", "organization_id"):+ team_organizations[team_id] = str(organization_id)+ owners = {team_organizations[team_id] for team_id in team_ids if team_id in team_organizations}+ return tuple(sorted({*organization_ids, *owners}))++@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)@skip_team_scope_auditdef revoke_blocklisted_gateway_credentials() -> None:@@ -132,8 +170,10 @@ def revoke_blocklisted_gateway_credentials() -> None:# 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+ # Enforced access rules do not depend on the flag, so their bans still need the sweep.+ if not security_is_enforced(SecuritySurface.AI_GATEWAY):+ logger.info("wizard_blocklist: no blocklist flag defined, skipping the sweep")+ returnresult = sweep_blocklisted_gateway_credentials()logger.info("wizard_blocklist: sweep complete",diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 3f571faff38b..1d765a2411a6 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -21,7 +21,7 @@ from posthog.scopes import ()from posthog.utils import get_instance_region-from products.security.backend.facade.api import shadow_check as security_shadow_check+from products.security.backend.facade.api import access_refused as security_access_refusedfrom products.security.backend.facade.contracts import SubjectInput as SecuritySubjectfrom products.security.backend.facade.enums import Surface as SecuritySurface@@ -688,7 +688,7 @@ def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:raise WizardIdentityBlockedError(WIZARD_BLOCKED_DETAIL)try:- security_shadow_check(+ refused = security_access_refused(SecuritySubject(email=user.email,user_uuid=str(user.uuid),@@ -698,7 +698,10 @@ def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:call_site="wizard_mint",)except Exception:- logger.exception("security_shadow_check_site_failed", call_site="wizard_mint")+ logger.exception("security_access_check_site_failed", call_site="wizard_mint")+ refused = False+ if refused:+ raise WizardIdentityBlockedError(WIZARD_BLOCKED_DETAIL)app = get_wizard_app()diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.pyindex 378c8678927d..f26ce570b478 100644--- a/posthog/temporal/tests/test_oauth.py+++ b/posthog/temporal/tests/test_oauth.py@@ -511,19 +511,26 @@ class TestCreateWizardOAuthAccessTokenForUser(TestCase):assert access_token.scoped_teams == [team.id]assert set(access_token.scope.split()) == set(scopes)+ @parameterized.expand([("allowed", False), ("refused", True)])@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)- @patch("posthog.temporal.oauth.security_shadow_check")- def test_mint_records_a_shadow_access_check(self, shadow: MagicMock) -> None:+ @patch("posthog.temporal.oauth.security_access_refused")+ def test_mint_asks_the_access_rules(self, _name: str, refused: bool, check: MagicMock) -> None:+ check.return_value = refusedself._create_wizard_app(scopes=["project:read", "llm_gateway:read"])user, team = self._create_user_and_team()- create_wizard_oauth_access_token_for_user(user, team.id)+ if refused:+ with pytest.raises(WizardIdentityBlockedError):+ create_wizard_oauth_access_token_for_user(user, team.id)+ else:+ create_wizard_oauth_access_token_for_user(user, team.id)- shadow.assert_called_once()- subject, surface = shadow.call_args.args+ check.assert_called_once()+ subject, surface = check.call_args.argsassert surface == SecuritySurface.AI_GATEWAYassert subject.organization_ids == (str(team.organization_id),)- assert shadow.call_args.kwargs == {"call_site": "wizard_mint"}+ assert check.call_args.kwargs == {"call_site": "wizard_mint"}+ assert OAuthAccessToken.objects.exists() is not refused@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)def test_requires_existing_app(self) -> None:diff --git a/products/security/backend/facade/api.py b/products/security/backend/facade/api.pyindex b0c0d1f15a34..8e9b9b8f2cf7 100644--- a/products/security/backend/facade/api.py+++ b/products/security/backend/facade/api.py@@ -14,9 +14,10 @@ import structlogfrom ..logic.accounts import email_for_userfrom ..logic.decisions import deciding_rule+from ..logic.enforcement import is_enforced as _is_enforcedfrom ..logic.snapshot import current_snapshotfrom ..logic.subjects import normalize_subject-from ..metrics import DECISION_ERRORS_COUNTER, DECISIONS_COUNTER, WOULD_BLOCK_COUNTER+from ..metrics import DECISION_ERRORS_COUNTER, DECISIONS_COUNTER, REFUSALS_COUNTER, WOULD_BLOCK_COUNTERfrom . import contractsfrom .enums import Outcome, Surface@@ -24,6 +25,10 @@ logger = structlog.get_logger(__name__)_OUTCOME_FOR_MATCH = {Surface.EMAIL_CODE: Outcome.EXEMPT, Surface.SIGNUP_RISK: Outcome.EXEMPT}+# The error code every refusal carries, so support can tell an access rule from any other 403+# without the response naming the rule that matched.+REFUSAL_CODE = "access_blocked"+def decide(subject: contracts.SubjectInput, surface: Surface) -> contracts.Decision:# Without the email, a posthog.com user named only by ID would skip the protection.@@ -77,23 +82,64 @@ def is_signup_risk_exempt(email: str) -> bool:return False+def is_enforced(surface: Surface) -> bool:+ """Whether a block rule refuses requests on this surface, rather than only recording them."""+ return _is_enforced(surface)+++def _record_block(+ decision: contracts.Decision, subject: contracts.SubjectInput, call_site: str, *, refused: bool+) -> None:+ counter = REFUSALS_COUNTER if refused else WOULD_BLOCK_COUNTER+ counter.labels(surface=decision.surface.value, call_site=call_site, target_type=decision.target_type or "").inc()+ logger.info(+ "security_access_refused" if refused else "security_access_would_block",+ surface=decision.surface.value,+ call_site=call_site,+ rule_id=decision.rule_id,+ target_type=decision.target_type,+ user_uuid=subject.user_uuid,+ )+++def access_refused(subject: contracts.SubjectInput, surface: Surface, *, call_site: str) -> bool:+ """Whether a block rule refuses this request.++ On a surface that is not enforced, a match only records a would-block and returns False.+ Never raises: a failed decision refuses nobody, so a broken check turns the blocklist off+ instead of locking everyone out. The error counter is what shows that it happened.+ """+ try:+ decision = _counted(decide(subject, surface), call_site)+ if decision.outcome != Outcome.BLOCK:+ return False+ refused = _is_enforced(surface)+ _record_block(decision, subject, call_site, refused=refused)+ return refused+ except Exception:+ logger.exception("security_access_check_failed", call_site=call_site)+ DECISION_ERRORS_COUNTER.labels(call_site=call_site).inc()+ return False++def shadow_check(subject: contracts.SubjectInput, surface: Surface, *, call_site: str) -> None:"""Records what a block rule would do here, and changes nothing. Never raises."""try:decision = _counted(decide(subject, surface), call_site)if decision.outcome != Outcome.BLOCK:return- WOULD_BLOCK_COUNTER.labels(- surface=surface.value, call_site=call_site, target_type=decision.target_type or ""- ).inc()- logger.info(- "security_access_would_block",- surface=surface.value,- call_site=call_site,- rule_id=decision.rule_id,- target_type=decision.target_type,- user_uuid=subject.user_uuid,- )+ _record_block(decision, subject, call_site, refused=False)except Exception:logger.exception("security_access_shadow_check_failed", call_site=call_site)DECISION_ERRORS_COUNTER.labels(call_site=call_site).inc()+++def gateway_credentials_revoked(subject: contracts.SubjectInput) -> bool:+ """Whether a block rule takes away the AI gateway credentials this identity already holds.++ Always False while the AI gateway is not enforced, so a rule in shadow mode never revokes+ anything and the sweep adds nothing to the would-block count. Never raises.+ """+ if not _is_enforced(Surface.AI_GATEWAY):+ return False+ return access_refused(subject, Surface.AI_GATEWAY, call_site="revoke_sweep")diff --git a/products/security/backend/logic/enforcement.py b/products/security/backend/logic/enforcement.pynew file mode 100644index 000000000000..560682c09a24--- /dev/null+++ b/products/security/backend/logic/enforcement.py@@ -0,0 +1,39 @@+import json+from typing import Any++import structlog+import posthoganalytics++from ..facade.enums import Surface++logger = structlog.get_logger(__name__)++# One flag in PostHog's own project. Its JSON payload names the surfaces where a block rule+# refuses requests, for example {"signup": true, "ai_gateway": false, "app": false}. Turning the+# flag off stops every refusal at once.+ENFORCEMENT_FLAG = "security-access-enforcement"+++def _enforcement_payload() -> dict[str, Any]:+ payload = posthoganalytics.get_feature_flag_payload(+ ENFORCEMENT_FLAG,+ ENFORCEMENT_FLAG,+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ if isinstance(payload, str):+ payload = json.loads(payload)+ return payload if isinstance(payload, dict) else {}+++def is_enforced(surface: Surface) -> bool:+ """Whether the enforcement flag turns refusals on for this surface.++ Reads the locally polled flag definitions, so it never waits on the network. Anything other+ than a literal true, including missing definitions or an error, leaves the surface logging only.+ """+ try:+ return _enforcement_payload().get(surface.value) is True+ except Exception:+ logger.warning("security_access_enforcement_flag_unreadable", exc_info=True)+ return Falsediff --git a/products/security/backend/metrics.py b/products/security/backend/metrics.pyindex f4af515c9097..6642fdb62a2d 100644--- a/products/security/backend/metrics.py+++ b/products/security/backend/metrics.py@@ -13,6 +13,11 @@ DECISIONS_COUNTER = Counter("Access decisions evaluated, by surface, call site and outcome",labelnames=["surface", "call_site", "outcome"],)+REFUSALS_COUNTER = Counter(+ "posthog_security_access_refusals_total",+ "Requests an access rule refused, on a surface that enforces blocks",+ labelnames=["surface", "call_site", "target_type"],+)DECISION_ERRORS_COUNTER = Counter("posthog_security_access_decision_errors_total","Access decisions that raised and were treated as allow",diff --git a/products/security/backend/tests/helpers.py b/products/security/backend/tests/helpers.pyindex 11bac06cf666..d2a1e5f368f3 100644--- a/products/security/backend/tests/helpers.py+++ b/products/security/backend/tests/helpers.py@@ -1,6 +1,10 @@+from collections.abc import Iterator+from contextlib import contextmanagerfrom itertools import countfrom typing import Any+from unittest.mock import patch+from products.security.backend.logic.snapshot import reset_memo, write_snapshot_ids = count(1)@@ -21,3 +25,13 @@ def exempt_rule(**overrides: Any) -> dict[str, Any]:def seed_rules(*rules: dict[str, Any]) -> None:write_snapshot(f"test-{next(_ids)}", list(rules))reset_memo()+++@contextmanager+def enforcing(*surfaces: str) -> Iterator[None]:+ """Turns refusals on for these surfaces, as the enforcement flag's payload would."""+ with patch(+ "products.security.backend.logic.enforcement._enforcement_payload",+ return_value=dict.fromkeys(surfaces, True),+ ):+ yielddiff --git a/products/security/backend/tests/test_facade.py b/products/security/backend/tests/test_facade.pyindex 24aef57bbdb6..6437e65884e0 100644--- a/products/security/backend/tests/test_facade.py+++ b/products/security/backend/tests/test_facade.py@@ -6,10 +6,18 @@ from prometheus_client import REGISTRYfrom posthog.models import User-from products.security.backend.facade.api import decide, is_email_code_exempt, is_signup_risk_exempt, shadow_check+from products.security.backend.facade.api import (+ access_refused,+ decide,+ gateway_credentials_revoked,+ is_email_code_exempt,+ is_enforced,+ is_signup_risk_exempt,+ shadow_check,+)from products.security.backend.facade.contracts import SubjectInputfrom products.security.backend.facade.enums import Outcome, Surface-from products.security.backend.tests.helpers import block_rule, exempt_rule, seed_rules+from products.security.backend.tests.helpers import block_rule, enforcing, exempt_rule, seed_rulesdef _would_block(call_site: str) -> float:@@ -32,6 +40,16 @@ def _decisions(surface: str, call_site: str, outcome: str) -> float:)+def _refusals(call_site: str) -> float:+ return (+ REGISTRY.get_sample_value(+ "posthog_security_access_refusals_total",+ {"surface": "app", "call_site": call_site, "target_type": "user_uuid"},+ )+ or 0.0+ )++class TestFacade(BaseTest):def test_a_uuid_only_subject_is_resolved_before_the_posthog_check(self) -> None:staff = User.objects.create_and_join(self.organization, "[email protected]", "password1234")@@ -104,3 +122,83 @@ class TestFacade(BaseTest):before = _decisions(surface, surface, outcome)check(address)assert _decisions(surface, surface, outcome) == before + 1++ @parameterized.expand(+ [+ ("surface enforced", ["app"], True),+ ("another surface enforced", ["signup", "ai_gateway"], False),+ ("nothing enforced", [], False),+ ]+ )+ def test_access_refused_only_on_an_enforced_surface(self, _name: str, enforced: list[str], expected: bool) -> None:+ user = User.objects.create_and_join(self.organization, "[email protected]", "password1234")+ seed_rules(block_rule(targetType="user_uuid", targetValue=str(user.uuid)))+ refused_before, would_block_before = _refusals("refuse_site"), _would_block("refuse_site")++ with enforcing(*enforced):+ result = access_refused(+ SubjectInput(email=user.email, user_uuid=str(user.uuid)), Surface.APP, call_site="refuse_site"+ )++ assert result is expected+ assert _refusals("refuse_site") == refused_before + (1 if expected else 0)+ assert _would_block("refuse_site") == would_block_before + (0 if expected else 1)++ def test_access_refused_refuses_nobody_when_the_decision_fails(self) -> None:+ seed_rules(block_rule(targetValue="[email protected]"))+ with (+ enforcing("app"),+ patch("products.security.backend.facade.api.current_snapshot", side_effect=RuntimeError("boom")),+ ):+ assert (+ access_refused(SubjectInput(email="[email protected]"), Surface.APP, call_site="refuse_site") is False+ )++ @parameterized.expand([("gateway enforced", ["ai_gateway"], True), ("gateway in shadow", ["signup", "app"], False)])+ def test_gateway_credentials_are_revoked_only_while_the_gateway_is_enforced(+ self, _name: str, enforced: list[str], expected: bool+ ) -> None:+ seed_rules(block_rule(targetValue="[email protected]", scope="ai_gateway"))+ would_block_before = REGISTRY.get_sample_value(+ "posthog_security_access_would_block_total",+ {"surface": "ai_gateway", "call_site": "revoke_sweep", "target_type": "email"},+ )++ with enforcing(*enforced):+ assert gateway_credentials_revoked(SubjectInput(email="[email protected]")) is expected++ # The sweep re-reads every credential every few minutes, so a would-block from it would+ # swamp the shadow data the flip depends on.+ assert (+ REGISTRY.get_sample_value(+ "posthog_security_access_would_block_total",+ {"surface": "ai_gateway", "call_site": "revoke_sweep", "target_type": "email"},+ )+ == would_block_before+ )++ @parameterized.expand(+ [+ ("payload turns the surface on", {"signup": True}, True),+ ("payload arrives as JSON text", '{"signup": true}', True),+ ("payload leaves the surface off", {"signup": False, "app": True}, False),+ ("a truthy value that is not true", {"signup": "false"}, False),+ ("no payload, or no definitions yet", None, False),+ ("payload that is not an object", '["signup"]', False),+ ]+ )+ def test_is_enforced_reads_only_a_literal_true_from_the_flag_payload(+ self, _name: str, payload: object, expected: bool+ ) -> None:+ with patch(+ "products.security.backend.logic.enforcement.posthoganalytics.get_feature_flag_payload",+ return_value=payload,+ ):+ assert is_enforced(Surface.SIGNUP) is expected++ def test_is_enforced_leaves_the_surface_logging_only_when_the_flag_cannot_be_read(self) -> None:+ with patch(+ "products.security.backend.logic.enforcement.posthoganalytics.get_feature_flag_payload",+ side_effect=RuntimeError("definitions unavailable"),+ ):+ assert is_enforced(Surface.SIGNUP) is Falsediff --git a/products/security/backend/tests/test_shadow_call_sites.py b/products/security/backend/tests/test_shadow_call_sites.pyindex 5c5a4bd47d1b..ddb226eba231 100644--- a/products/security/backend/tests/test_shadow_call_sites.py+++ b/products/security/backend/tests/test_shadow_call_sites.py@@ -1,11 +1,24 @@+import pytestfrom posthog.test.base import APIBaseTest+from unittest.mock import MagicMock+from django.test import RequestFactory+from django.utils import timezone++from parameterized import parameterizedfrom prometheus_client import REGISTRY+from social_core.exceptions import AuthFailed+from posthog.api.signup import (+ process_social_domain_jit_provisioning_signup,+ process_social_invite_signup,+ signup_refused,+)from posthog.models import Organization, User+from posthog.models.organization_domain import OrganizationDomainfrom posthog.models.organization_invite import OrganizationInvite-from products.security.backend.tests.helpers import block_rule, seed_rules+from products.security.backend.tests.helpers import block_rule, enforcing, seed_rulesdef _count(surface: str, call_site: str, target_type: str) -> float:@@ -22,24 +35,29 @@ class TestShadowCallSites(APIBaseTest):# The default test user is a posthog.com account, which no block rule may reach.CONFIG_EMAIL = "[email protected]"- def test_blocked_signup_is_logged_and_still_succeeds(self) -> None:+ @parameterized.expand([("logged only", [], 201, 1), ("enforced", ["signup"], 403, 0)])+ def test_blocked_signup(self, _name: str, enforced: list[str], status: int, would_block: int) -> None:seed_rules(block_rule(targetType="email_domain", targetValue="throwaway.example", scope="signup"))before = _count("signup", "signup", "email_domain")self.client.logout()# CanCreateOrg only opens outside cloud/DEBUG when no organization exists yet;# setUpTestData already created one, so this test's own org must go first.self.organization.delete()- response = self.client.post(- "/api/signup/",- {- "email": "[email protected]",- "password": "a-long-password-123",- "first_name": "New",- "organization_name": "Org",- },- )- assert response.status_code == 201, response.json()- assert _count("signup", "signup", "email_domain") == before + 1+ with enforcing(*enforced):+ response = self.client.post(+ "/api/signup/",+ {+ "email": "[email protected]",+ "password": "a-long-password-123",+ "first_name": "New",+ "organization_name": "Org",+ },+ )+ assert response.status_code == status, response.json()+ assert _count("signup", "signup", "email_domain") == before + would_block+ assert User.objects.filter(email="[email protected]").exists() is (status == 201)+ if status == 403:+ assert response.json()["code"] == "access_blocked"def test_blocked_login_is_logged_and_still_succeeds(self) -> None:user = User.objects.create_and_join(self.organization, "[email protected]", "a-long-password-123")@@ -52,7 +70,10 @@ class TestShadowCallSites(APIBaseTest):assert response.status_code == 200, response.json()assert _count("app", "login", "user_uuid") == before + 1- def test_blocked_existing_user_accepting_an_invite_is_logged_and_still_succeeds(self) -> None:+ @parameterized.expand([("logged only", [], 201, 1), ("enforced", ["signup"], 403, 0)])+ def test_blocked_existing_user_accepting_an_invite(+ self, _name: str, enforced: list[str], status: int, would_block: int+ ) -> None:# self.user (already logged in) is created with CONFIG_EMAIL, so this exercises the# branch InviteSignupSerializer.create takes when the invite acceptor already has an account.seed_rules(block_rule(targetType="email", targetValue=self.CONFIG_EMAIL))@@ -60,10 +81,11 @@ class TestShadowCallSites(APIBaseTest):invite = OrganizationInvite.objects.create(target_email=self.user.email, organization=new_org)before = _count("signup", "invite_signup", "email")- with self.captureOnCommitCallbacks(execute=True):+ with enforcing(*enforced), self.captureOnCommitCallbacks(execute=True):response = self.client.post(f"/api/signup/{invite.id}/")- assert response.status_code == 201, response.json()- assert _count("signup", "invite_signup", "email") == before + 1+ assert response.status_code == status, response.json()+ assert _count("signup", "invite_signup", "email") == before + would_block+ assert self.user.organizations.filter(id=new_org.id).exists() is (status == 201)def test_blocked_session_is_logged_and_still_served(self) -> None:seed_rules(block_rule(targetType="email", targetValue=self.user.email.lower()))@@ -77,3 +99,55 @@ class TestShadowCallSites(APIBaseTest):before = _count("app", "session", "email")assert self.client.get("/api/users/@me/").status_code == 200assert _count("app", "session", "email") == before++ def _sso_join(self, path: str, email: str, user: User | None, organization: Organization) -> None:+ strategy = MagicMock(request=RequestFactory().get("/complete/google-oauth2/"))+ if path == "invite":+ invite = OrganizationInvite.objects.create(target_email=email, organization=organization)+ process_social_invite_signup(strategy, str(invite.id), email, "Joiner", user, backend=MagicMock())+ else:+ OrganizationDomain.objects.create(+ organization=organization,+ domain="jit.example",+ verified_at=timezone.now(),+ jit_provisioning_enabled=True,+ )+ process_social_domain_jit_provisioning_signup(strategy, email, "Joiner", user, backend=MagicMock())++ @parameterized.expand(+ [+ ("invite, existing account, logged only", "invite", False, [], False),+ ("invite, existing account, enforced", "invite", False, ["signup"], True),+ ("invite, new account, enforced", "invite", True, ["signup"], True),+ ("verified domain, existing account, logged only", "jit", False, [], False),+ ("verified domain, existing account, enforced", "jit", False, ["signup"], True),+ ]+ )+ def test_blocked_sso_join(+ self, _name: str, path: str, new_account: bool, enforced: list[str], refused: bool+ ) -> None:+ # Invite and verified-domain joins over SSO never reach the signup serializers.+ email = "[email protected]"+ seed_rules(block_rule(targetValue=email, scope="signup"))+ joined = Organization.objects.create(name="Joined org")+ user = None if new_account else User.objects.create_and_join(self.organization, email, None)++ with enforcing(*enforced):+ if refused:+ with pytest.raises(AuthFailed, match="access_blocked"):+ self._sso_join(path, email, user, joined)+ else:+ self._sso_join(path, email, user, joined)++ assert joined.members.filter(email=email).exists() is not refused++ @parameterized.expand([("logged only", [], False, 1), ("enforced", ["signup"], True, 0)])+ def test_partner_signup(self, _name: str, enforced: list[str], refused: bool, would_block: int) -> None:+ # Partner provisioning (agentic, Stripe, Vercel) creates accounts outside the signup serializers.+ seed_rules(block_rule(targetType="email_domain", targetValue="throwaway.example", scope="signup"))+ before = _count("signup", "agentic_provisioning", "email_domain")++ with enforcing(*enforced):+ assert signup_refused("[email protected]", call_site="agentic_provisioning") is refused++ assert _count("signup", "agentic_provisioning", "email_domain") == before + would_blockdiff --git a/products/tasks/backend/presentation/views/desktop_access.py b/products/tasks/backend/presentation/views/desktop_access.pyindex 49c24a1629b0..26fa60b1d9cd 100644--- a/products/tasks/backend/presentation/views/desktop_access.py+++ b/products/tasks/backend/presentation/views/desktop_access.py@@ -23,7 +23,11 @@ from posthog.models.oauth import OAuthAccessTokenfrom posthog.permissions import APIScopePermissionfrom posthog.storage.gateway_credential_cache import GATEWAY_CREDENTIAL_REQUIRED_SCOPE, oauth_credential_authorizedfrom posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDS+from posthog.utils import get_trusted_client_ip+from products.security.backend.facade.api import access_refused as security_access_refused+from products.security.backend.facade.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurfacefrom products.tasks.backend.facade.access import (DesktopAccessResolutionError,compute_quota_limit_response,@@ -237,6 +241,23 @@ class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):surface="desktop_gateway_token",):return _disabled("blocked", status.HTTP_403_FORBIDDEN, detail="This account cannot use the AI gateway.")+ try:+ refused = security_access_refused(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ organization_ids=(str(organization.id),),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.AI_GATEWAY,+ call_site="desktop_gateway_token",+ )+ except Exception as e:+ capture_exception(e)+ refused = False+ if refused:+ # The flag's refusal, word for word, so a client cannot tell which blocklist matched.+ return _disabled("blocked", status.HTTP_403_FORBIDDEN, detail="This account cannot use the AI gateway.")if not desktop_gateway_configured():return _disabled("unconfigured")diff --git a/products/tasks/backend/tests/test_desktop_gateway_token.py b/products/tasks/backend/tests/test_desktop_gateway_token.pyindex b9d6e3cdd291..8d8aea553f74 100644--- a/products/tasks/backend/tests/test_desktop_gateway_token.py+++ b/products/tasks/backend/tests/test_desktop_gateway_token.py@@ -106,6 +106,7 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):"credit": patch(f"{_VIEW}.team_credit_refusal", return_value=None),"blocked": patch(f"{_VIEW}.wizard_identity_blocked", return_value=False),"tier": patch(f"{_VIEW}.desktop_limit_tier", return_value="standard"),+ "rules": patch(f"{_VIEW}.security_access_refused", return_value=False),}self.mocks = {name: patcher.start() for name, patcher in self.gates.items()}for patcher in self.gates.values():@@ -205,6 +206,22 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):surface="desktop_gateway_token",)+ def test_an_access_rule_refusal_is_refused_before_the_rollout(self) -> None:+ self.mocks["rules"].return_value = True+ response, post = self._mint()+ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert response.json() == {+ "enabled": False,+ "reason": "blocked",+ "detail": "This account cannot use the AI gateway.",+ }+ self.mocks["rollout"].assert_not_called()+ post.assert_not_called()+ subject, surface = self.mocks["rules"].call_args.args+ assert surface.value == "ai_gateway"+ assert subject.organization_ids == (str(self.organization.id),)+ assert self.mocks["rules"].call_args.kwargs == {"call_site": "desktop_gateway_token"}+@override_settings(DESKTOP_GATEWAY_MINT_KEY="")def test_unconfigured_is_disabled(self) -> None:response, post = self._mint()diff --git a/products/wizard/backend/presentation/runs/views.py b/products/wizard/backend/presentation/runs/views.pyindex ffc4537ebd72..946e94d88f37 100644--- a/products/wizard/backend/presentation/runs/views.py+++ b/products/wizard/backend/presentation/runs/views.py@@ -6,6 +6,7 @@ from django.conf import settingsfrom django.http import HttpResponsefrom django.http.response import HttpResponseBase+import structlogfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsetsfrom rest_framework.exceptions import NotFound, PermissionDenied@@ -17,7 +18,13 @@ from posthog.api.streaming import sse_streaming_responsefrom posthog.api.utils import actionfrom posthog.auth import OAuthAccessTokenAuthentication, SessionAuthenticationfrom posthog.exceptions import Conflict+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL+from posthog.models import User+from posthog.utils import get_trusted_client_ip+from products.security.backend.facade.api import access_refused as security_access_refused+from products.security.backend.facade.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurfacefrom products.wizard.backend.facade import api as wizard_facadefrom products.wizard.backend.facade.contracts import WizardRunDTOfrom products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus@@ -41,6 +48,8 @@ from products.wizard.backend.presentation.runs.stream import wizard_run_event_stfrom products.wizard.backend.presentation.sessions.views import EventStreamRenderer, _wizard_sync_killswitch_enabledfrom products.wizard.backend.presentation.throttles import WizardRunCreateThrottle, WizardRunReadThrottle+logger = structlog.get_logger(__name__)+class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""@@ -115,6 +124,7 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if params.environment == WizardRunEnvironment.CLOUD:self._validate_cloud_creation(request)+ self._refuse_blocked_gateway_identity(request)try:result = wizard_facade.create_run_with_result(params)@@ -125,6 +135,30 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return Response(WizardRunSerializer(result.run).data, status=response_status)+ def _refuse_blocked_gateway_identity(self, request: Request) -> None:+ """Refuse a cloud run to an identity an enforced AI gateway rule blocks.++ The run mints its gateway token later, in a workflow with no request, so this is the only+ point where a rule on the caller's IP can match.+ """+ user = cast(User, request.user)+ try:+ refused = security_access_refused(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ organization_ids=(str(self.team.organization_id),),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.AI_GATEWAY,+ call_site="wizard_run",+ )+ except Exception:+ logger.exception("security_access_check_site_failed", call_site="wizard_run")+ refused = False+ if refused:+ raise PermissionDenied(WIZARD_BLOCKED_DETAIL)+@staticmethoddef _validate_cloud_creation(request: Request) -> None:if not settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID:diff --git a/products/wizard/backend/tests/runs/test_presentation.py b/products/wizard/backend/tests/runs/test_presentation.pyindex e3a1398d6849..938a6553d314 100644--- a/products/wizard/backend/tests/runs/test_presentation.py+++ b/products/wizard/backend/tests/runs/test_presentation.py@@ -13,6 +13,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAILfrom posthog.models import PersonalAPIKey, Team, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -332,6 +333,35 @@ class TestWizardRunViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["detail"], "Connect GitHub with access to this repository, then try again.")+ @parameterized.expand([("allowed", False, status.HTTP_201_CREATED), ("refused", True, status.HTTP_403_FORBIDDEN)])+ @patch(+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",+ return_value=True,+ )+ @patch(+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",+ return_value=123,+ )+ def test_cloud_run_asks_the_access_rules_with_the_caller_ip(+ self, _name: str, refused: bool, expected_status: int, _resolve_integration, _repository_accessible+ ) -> None:+ # The run mints its gateway token later with no request, so an IP rule only matches here.+ with patch(+ "products.wizard.backend.presentation.runs.views.security_access_refused", return_value=refused+ ) as check:+ response = self.client.post(+ self._url(), self._cloud_payload(idempotency_key=f"rules-{_name}"), format="json"+ )++ self.assertEqual(response.status_code, expected_status, response.content)+ subject, surface = check.call_args.args+ self.assertEqual(surface.value, "ai_gateway")+ self.assertEqual(check.call_args.kwargs, {"call_site": "wizard_run"})+ self.assertIsNotNone(subject.ip)+ self.assertEqual(subject.organization_ids, (str(self.team.organization_id),))+ if refused:+ self.assertEqual(response.json()["detail"], WIZARD_BLOCKED_DETAIL)+@patch("products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",return_value=True,diff --git a/tach.toml b/tach.tomlindex e3cdaf6fe371..ff0bdb661d0e 100644--- a/tach.toml+++ b/tach.toml@@ -70,6 +70,7 @@ depends_on = ["products.replay_vision","products.skills","products.revenue_analytics",+ "products.security","products.surveys","products.tasks","products.business_knowledge",@@ -982,6 +983,7 @@ depends_on = [# product has no facade, so this matches how review_hog and signals reach LLMSkill."products.skills","products.slack_app", "products.access_control",+ "products.security",]layer = "modules"@@ -1391,7 +1393,7 @@ from = [[[modules]]path = "products.wizard"-depends_on = ["posthog", "products.event_definitions", "products.tasks"]+depends_on = ["posthog", "products.event_definitions", "products.security", "products.tasks"]layer = "modules"[[interfaces]]