: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): log would-be blocks at sign-in, session and gateway call sites (#103580)
Yasenf92e94be2057
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex d79faa6d41ea..a6a5e4afcf47 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -88,9 +88,18 @@ from posthog.tasks.email import (send_password_reset,send_two_factor_auth_backup_code_used_email,)-from posthog.utils import get_instance_available_sso_providers, get_ip_address, get_short_user_agent+from posthog.utils import (+ get_instance_available_sso_providers,+ get_ip_address,+ get_short_user_agent,+ get_trusted_client_ip,+)from posthog.workos_radar import RadarAction, RadarAuthMethod, evaluate_auth_attempt+from products.security.backend.facade.api import shadow_check as security_shadow_check+from products.security.backend.facade.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurface+logger = structlog.get_logger("posthog.auth")mfa_logger = structlog.get_logger("posthog.auth.mfa")@@ -354,6 +363,15 @@ class LoginSerializer(serializers.Serializer):raise serializers.ValidationError("Invalid email or password.", code="invalid_credentials")+ try:+ security_shadow_check(+ SecuritySubject(email=user.email, user_uuid=str(user.uuid), ip=get_trusted_client_ip(axes_request)),+ SecuritySurface.APP,+ call_site="login",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="login")+if not is_email_verified_for_login(user):# A fresh code was just emailed; hand the frontend the uuid so it can route to# the code entry page.diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex e02d137c5ff6..6d687eea401b 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -11,7 +11,7 @@ from urllib.parse import parse_qs, quote, urlencode, urlparse, urlunparseimport pytestimport time_machinefrom posthog.test.base import APIBaseTest, FuzzyInt-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.conf import settingsfrom django.db import OperationalError@@ -54,6 +54,7 @@ from posthog.settings.utils import generate_rsa_private_key_pemfrom posthog.utils import absolute_urifrom products.access_control.backend.models.access_control import AccessControl+from products.security.backend.facade.enums import Surface as SecuritySurface# A cut-off `scope` parameter only reads as truncated once enough real scopes come through# before the fragment, so a fixture standing in for one has to be that long.@@ -3440,6 +3441,27 @@ 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:+ 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+ self.assertEqual(surface, SecuritySurface.AI_GATEWAY)+ self.assertEqual(subject.user_uuid, str(self.user.uuid))+ self.assertEqual(shadow.call_args.kwargs, {"call_site": "oauth_authorize"})++ @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:+ 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())+ shadow.assert_called_once()+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 thediff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 9776c3bd1a6b..588419340eb8 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -99,10 +99,13 @@ from posthog.scopes import ()from posthog.security.url_validation import has_ambiguous_authorityfrom posthog.user_permissions import UserPermissions-from posthog.utils import absolute_uri, get_instance_region, render_template+from posthog.utils import absolute_uri, get_instance_region, get_trusted_client_ip, render_templatefrom 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.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurfacelogger = structlog.get_logger(__name__)@@ -348,6 +351,19 @@ def _gateway_blocklist_block(if not GATEWAY_BEARING_SCOPES & requested:return Noneorganization_ids = _scoped_organization_ids(request.user, access_level, scoped_organization_ids, scoped_team_ids)+ try:+ security_shadow_check(+ SecuritySubject(+ email=request.user.email,+ user_uuid=str(request.user.uuid),+ organization_ids=tuple(str(organization_id) for organization_id in organization_ids),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.AI_GATEWAY,+ call_site="oauth_authorize",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="oauth_authorize")if not wizard_identity_blocked(distinct_id=str(request.user.distinct_id),email=request.user.email,diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 2632cc758c91..34f08996c71c 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -46,6 +46,9 @@ 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.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurfacelogger = structlog.get_logger(__name__)@@ -232,6 +235,18 @@ class SignupSerializer(serializers.Serializer):challenge_nonce=validated_data.get("challenge_nonce", ""),)+ try:+ security_shadow_check(+ SecuritySubject(+ email=validated_data["email"],+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.SIGNUP,+ call_site="signup",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="signup")+is_instance_first_user: bool = not User.objects.exists()validated_data.pop("turnstile_token", None)@@ -579,6 +594,21 @@ class InviteSignupSerializer(serializers.Serializer):code="verified_domain_required",)+ # 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(+ SecuritySubject(+ email=(user.email if user else invite.target_email) or "",+ user_uuid=str(user.uuid) if user else None,+ ip=get_trusted_client_ip(getattr(self.context["request"], "_request", self.context["request"])),+ ),+ SecuritySurface.SIGNUP,+ call_site="invite_signup",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="invite_signup")+with transaction.atomic():if not user:is_new_user = Truediff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex e8423caabeaf..95b0658e37aa 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -46,7 +46,11 @@ from posthog.storage.gateway_credential_cache import (oauth_credential_authorized,)from posthog.user_permissions import UserPermissions+from 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.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurfacefrom products.tasks.backend.facade import api as tasks_facadelogger = structlog.get_logger(__name__)@@ -254,6 +258,20 @@ class SetupWizardViewSet(viewsets.ViewSet):# Ahead of the rollout gate, so a ban reads as a ban whatever the flag says.refuse("blocked", exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL), user=user)+ try:+ security_shadow_check(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ organization_ids=(str(team.organization_id),),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.AI_GATEWAY,+ call_site="wizard_gateway_token",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="wizard_gateway_token")+# 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# rolled out" turns a flag-service blip into a global wizard outage.@@ -424,6 +442,20 @@ class SetupWizardViewSet(viewsets.ViewSet):# permission_denied.raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)+ try:+ security_shadow_check(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ organization_ids=(str(project.organization_id),),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.AI_GATEWAY,+ call_site="wizard_cloud_run",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="wizard_cloud_run")+self._reserve_cloud_run_attempt(user.id)try:diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex d46f8e4051a4..1faa1e4add34 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -23,6 +23,8 @@ from posthog.models import Organization, PersonalAPIKey, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import SetupWizardGatewayTokenRateThrottle, refund_wizard_mint, reserve_wizard_mint+from products.security.backend.facade.enums import Surface as SecuritySurface+# Derived, not written out: these cases assert the ceiling binds, not its value.# Every floor populates every field; the Optional is there for partial overrides._active_mints = _TIER_FLOORS["active"].mints_per_week@@ -74,6 +76,24 @@ class SetupWizardCloudRunTests(APIBaseTest):assert kwargs["branch"] is Noneassert kwargs["team"].id == self.team.id+ @patch("posthog.api.wizard.http.security_shadow_check")+ @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:+ mock_create.return_value = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))++ response = self.client.post(+ self.CLOUD_RUN_URL,+ data={"project_id": self.team.id, "repository": "acme/app", "branch": ""},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ shadow.assert_called_once()+ subject, surface = shadow.call_args.args+ assert surface == SecuritySurface.AI_GATEWAY+ assert subject.organization_ids == (str(self.team.organization_id),)+ assert shadow.call_args.kwargs == {"call_site": "wizard_cloud_run"}+@patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")def test_rejects_invalid_repository_format(self, mock_create):response = self.client.post(@@ -288,6 +308,27 @@ class SetupWizardGatewayTokenTests(APIBaseTest):"posture": "new",}+ @patch("posthog.api.wizard.http.security_shadow_check")+ @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+ ) -> None:+ self._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 surface == SecuritySurface.AI_GATEWAY+ assert subject.organization_ids == (str(self.team.organization_id),)+ assert shadow.call_args.kwargs == {"call_site": "wizard_gateway_token"}+@override_settings(DEBUG=False, WIZARD_GATEWAY_TIERS={"new": {"mints_per_week": 2}})@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)diff --git a/posthog/auth.py b/posthog/auth.pyindex ecb195e4061c..c441e3fa1033 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -60,9 +60,13 @@ from posthog.passkey import verify_passkey_authentication_responsefrom posthog.scoped_service_jwt import ScopedServiceJwtPurposefrom posthog.shared_link_user import SharedLinkUserfrom posthog.synthetic_user import SyntheticUser+from posthog.utils import get_trusted_client_ipfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.exports.backend.facade.auth import get_export_renderer_asset_context+from products.security.backend.facade.api import shadow_check as security_shadow_check+from products.security.backend.facade.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurfacefrom products.signals.backend.facade.activity_client import resolve_scout_client_tag@@ -184,6 +188,18 @@ class SessionAuthentication(authentication.SessionAuthentication):user, auth = auth_resultenforce_two_factor(request, user)enforce_verified_domain(request, user)+ try:+ security_shadow_check(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.APP,+ call_site="session",+ )+ except Exception:+ structlog_logger.exception("security_shadow_check_site_failed", call_site="session")return (user, auth)diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex db75e74b2230..318784828f19 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -22,6 +22,10 @@ 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.contracts import SubjectInput as SecuritySubject+from products.security.backend.facade.enums import Surface as SecuritySurface+logger = structlog.get_logger(__name__)ARRAY_APP_CLIENT_ID_US = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W"@@ -625,16 +629,30 @@ def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:Gated here rather than only at the HTTP kickoff, which a workflow retry orresume reaches with no request in front of it."""+ organization_id = _organization_id_for_team(team_id)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)],+ organization_ids=[organization_id],team_ids=[team_id],):raise WizardIdentityBlockedError(WIZARD_BLOCKED_DETAIL)+ try:+ security_shadow_check(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ organization_ids=(organization_id,),+ ),+ SecuritySurface.AI_GATEWAY,+ call_site="wizard_mint",+ )+ except Exception:+ logger.exception("security_shadow_check_site_failed", call_site="wizard_mint")+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.pyindex ffa559ffa5b5..387723fbeeca 100644--- a/posthog/temporal/tests/test_oauth.py+++ b/posthog/temporal/tests/test_oauth.py@@ -4,7 +4,7 @@ from typing import castfrom uuid import uuid4import pytest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, TestCase, override_settings@@ -39,6 +39,8 @@ from posthog.temporal.oauth import (scout_scope_posture,)+from products.security.backend.facade.enums import Surface as SecuritySurface+_WIZARD_CLIENT_ID = "wizard-test-client-id"@@ -492,6 +494,20 @@ class TestCreateWizardOAuthAccessTokenForUser(TestCase):assert access_token.scoped_teams == [team.id]assert set(access_token.scope.split()) == set(scopes)+ @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:+ self._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)++ shadow.assert_called_once()+ subject, surface = shadow.call_args.args+ assert surface == SecuritySurface.AI_GATEWAY+ assert subject.organization_ids == (str(team.organization_id),)+ assert shadow.call_args.kwargs == {"call_site": "wizard_mint"}+@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)def test_requires_existing_app(self) -> None:user, team = self._create_user_and_team()diff --git a/products/security/backend/tests/test_shadow_call_sites.py b/products/security/backend/tests/test_shadow_call_sites.pynew file mode 100644index 000000000000..5c5a4bd47d1b--- /dev/null+++ b/products/security/backend/tests/test_shadow_call_sites.py@@ -0,0 +1,79 @@+from posthog.test.base import APIBaseTest++from prometheus_client import REGISTRY++from posthog.models import Organization, User+from posthog.models.organization_invite import OrganizationInvite++from products.security.backend.tests.helpers import block_rule, seed_rules+++def _count(surface: str, call_site: str, target_type: str) -> float:+ return (+ REGISTRY.get_sample_value(+ "posthog_security_access_would_block_total",+ {"surface": surface, "call_site": call_site, "target_type": target_type},+ )+ or 0.0+ )+++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:+ 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++ 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")+ seed_rules(block_rule(targetType="user_uuid", targetValue=str(user.uuid)))+ before = _count("app", "login", "user_uuid")+ self.client.logout()+ response = self.client.post(+ "/api/login", {"email": "[email protected]", "password": "a-long-password-123"}+ )+ 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:+ # 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))+ new_org = Organization.objects.create(name="Other Org")+ invite = OrganizationInvite.objects.create(target_email=self.user.email, organization=new_org)++ before = _count("signup", "invite_signup", "email")+ with 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++ def test_blocked_session_is_logged_and_still_served(self) -> None:+ seed_rules(block_rule(targetType="email", targetValue=self.user.email.lower()))+ before = _count("app", "session", "email")+ response = self.client.get("/api/users/@me/")+ assert response.status_code == 200+ assert _count("app", "session", "email") == before + 1++ def test_unmatched_requests_log_nothing(self) -> None:+ seed_rules(block_rule(targetValue="[email protected]"))+ before = _count("app", "session", "email")+ assert self.client.get("/api/users/@me/").status_code == 200+ assert _count("app", "session", "email") == before