: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 login and app sessions (#110813)
Yasenc7e8affbb7eb
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.pyindex 3e9828d79292..127038e061ff 100644--- a/ee/api/agentic_provisioning/authentication.py+++ b/ee/api/agentic_provisioning/authentication.py@@ -18,10 +18,13 @@ from posthog.api.oauth.client_assertion import (verify_client_assertion,)from posthog.api.oauth.client_auth import ClientCredentials, extract_client_credentials, verify_client_secret+from posthog.auth import ACCOUNT_BLOCKED_DETAIL, account_refusedfrom posthog.models.activity_logging.utils import ActivityCredentialMixinfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_tokenfrom posthog.models.user import User+from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODE+from ee.api.agentic_provisioning.analytics import capture_auth_eventfrom ee.api.agentic_provisioning.exceptions import ProvisioningError@@ -238,6 +241,13 @@ class ProvisioningBearerAuthentication(ActivityCredentialMixin, BaseAuthenticatiuser = access_token.userif user is None or not user.is_active:raise ProvisioningError("unauthorized", "Authentication failed", status=401)+ if account_refused(+ request,+ user,+ call_site="agentic_provisioning_token",+ impersonated=access_token.impersonated_by_id is not None,+ ):+ raise ProvisioningError(SECURITY_REFUSAL_CODE, ACCOUNT_BLOCKED_DETAIL, status=403)self.record_activity_actor(user, str(access_token.application_id), impersonated_by_id=access_token.impersonated_by_iddiff --git a/ee/api/agentic_provisioning/test/test_deep_links.py b/ee/api/agentic_provisioning/test/test_deep_links.pyindex 69db3aeb0fed..65b17559af74 100644--- a/ee/api/agentic_provisioning/test/test_deep_links.py+++ b/ee/api/agentic_provisioning/test/test_deep_links.py@@ -23,6 +23,15 @@ class TestDeepLinks(ProvisioningTestBase):assert "expires_at" in dataassert "token=" in data["url"]+ def test_deep_link_refused_when_an_access_rule_blocks_the_account(self):+ token = self._get_bearer_token()+ with patch("ee.api.agentic_provisioning.authentication.account_refused", return_value=True):+ res = self._post_with_bearer(+ "/api/agentic/provisioning/deep_links", data={"purpose": "dashboard"}, token=token+ )+ assert res.status_code == 403+ assert res.json()["error"]["code"] == "access_blocked"+def test_deep_link_url_contains_team_id(self):token = self._get_bearer_token()res = self._post_with_bearer(@@ -247,6 +256,14 @@ class TestAgenticLogin(ProvisioningTestBase):res = self.client.get("/api/users/@me/")assert res.status_code == 401+ def test_blocked_account_lands_on_login_without_a_session(self):+ token = self._create_deep_link_token()+ with patch("ee.api.agentic_provisioning.views.deep_links.account_refused", return_value=True):+ res = self.client.get(f"/agentic/login?token={token}")+ assert res.status_code == 302+ assert res["Location"] == "/login?error_code=access_blocked"+ assert self.client.get("/api/users/@me/").status_code == 401+def test_path_token_redirects_to_path(self):token = "test_path_token"target = f"/project/{self.team.id}/replay/abc123-DEF"diff --git a/ee/api/agentic_provisioning/views/deep_links.py b/ee/api/agentic_provisioning/views/deep_links.pyindex 04a56d672756..788a5cade7b6 100644--- a/ee/api/agentic_provisioning/views/deep_links.py+++ b/ee/api/agentic_provisioning/views/deep_links.py@@ -19,6 +19,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.email_verification import email_verification_code_verifier+from posthog.auth import ACCOUNT_BLOCKED_LOGIN_URL, account_refusedfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.oauth import OAuthAccessTokenfrom posthog.models.oauth_provisioning import PartnerTier@@ -186,6 +187,10 @@ def agentic_login(request: Any) -> HttpResponseBase:logger.warning("agentic_login.user_inactive", user_id=user_id)return HttpResponseRedirect("/?error=user_inactive")+ if account_refused(request, user, call_site="agentic_deep_link", impersonated=False):+ capture_deep_link_event("access_blocked", user_id=user_id)+ return HttpResponseRedirect(ACCOUNT_BLOCKED_LOGIN_URL)+# Deep-link login has no password challenge and no SSO step, so partner-asserted# email ownership is the only thing standing between an attacker and a session.# Require explicit is_email_verified=True - don't trust the legacy None passthroughdiff --git a/ee/api/vercel/test/test_vercel_sso.py b/ee/api/vercel/test/test_vercel_sso.pyindex ffb9e713868e..43fe00e5064f 100644--- a/ee/api/vercel/test/test_vercel_sso.py+++ b/ee/api/vercel/test/test_vercel_sso.py@@ -381,6 +381,20 @@ class TestSSOUserMapping:sso_setup["installation"], "existing_user_123", sso_setup["user"].pk)+ def test_sso_redirect_sends_a_blocked_account_to_login_without_a_session(self, sso_setup):+ sso_setup["installation"].config["user_mappings"] = {"existing_user_123": sso_setup["user"].pk}+ sso_setup["installation"].save()++ with (+ mock_vercel_integration(**MockFactory.successful_sso_flow(sso_setup["installation_id"])),+ mock_jwt_validation(create_user_claims(sso_setup["installation_id"], "existing_user_123")),+ patch("ee.vercel.integration.account_refused", return_value=True),+ ):+ response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])++ SSOTestHelper.assert_successful_redirect(response, "/login?error_code=access_blocked")+ assert "_auth_user_id" not in sso_setup["client"].session+def test_sso_redirect_sends_a_mapped_user_with_another_email_to_login_without_an_email(self, sso_setup):sso_setup["installation"].config["user_mappings"] = {"existing_user_123": sso_setup["user"].pk}sso_setup["installation"].save()diff --git a/ee/partners/stripe/api/provisioning/authentication.py b/ee/partners/stripe/api/provisioning/authentication.pyindex e1bd8210554f..325647916cc3 100644--- a/ee/partners/stripe/api/provisioning/authentication.py+++ b/ee/partners/stripe/api/provisioning/authentication.py@@ -17,13 +17,23 @@ from django.utils import timezonefrom rest_framework.authentication import BaseAuthenticationfrom rest_framework.request import Request+from posthog.auth import account_refusedfrom posthog.models.activity_logging.utils import ActivityCredentialMixinfrom posthog.models.oauth import OAuthAccessToken, find_oauth_access_tokenfrom posthog.models.user import User+from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODE+from ee.partners.stripe.api.provisioning.core import is_stripe_oauth_appfrom ee.partners.stripe.api.provisioning.exceptions import SpecError+# The response reaches Stripe, not a PostHog page, so the message names PostHog. The code is+# what lets PostHog support trace the refusal to an access rule.+ACCOUNT_BLOCKED_MESSAGE = (+ "PostHog can't give access to this account. If you think this is a mistake, contact PostHog support "+ f"and quote the code {SECURITY_REFUSAL_CODE}."+)+class StripeBearerAuthentication(ActivityCredentialMixin, BaseAuthentication):"""Authenticate the Stripe orchestrator via an OAuth bearer token.@@ -65,6 +75,14 @@ class StripeBearerAuthentication(ActivityCredentialMixin, BaseAuthentication):user = access_token.userif user is None or not user.is_active:raise SpecError("unauthorized", "Authentication failed", status=401)+ if account_refused(+ request,+ user,+ call_site="stripe_provisioning_token",+ impersonated=access_token.impersonated_by_id is not None,+ ):+ # Stripe's provisioning spec defines the error codes, so the refusal uses its `forbidden`.+ raise SpecError("forbidden", ACCOUNT_BLOCKED_MESSAGE, status=403)self.record_activity_actor(user, str(access_token.application_id), impersonated_by_id=access_token.impersonated_by_iddiff --git a/ee/partners/stripe/api/provisioning/login.py b/ee/partners/stripe/api/provisioning/login.pyindex a43ac462478a..03cebecf0639 100644--- a/ee/partners/stripe/api/provisioning/login.py+++ b/ee/partners/stripe/api/provisioning/login.py@@ -22,6 +22,7 @@ from django.utils.http import urlencodeimport structlogfrom posthog.api.email_verification import email_verification_code_verifier+from posthog.auth import ACCOUNT_BLOCKED_LOGIN_URL, account_refusedfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -137,6 +138,10 @@ def stripe_provisioning_login(request: Any) -> HttpResponseBase:logger.warning("stripe_provisioning.login.user_inactive", user_id=user_id)return HttpResponseRedirect("/?error=user_inactive")+ if account_refused(request, user, call_site="stripe_deep_link", impersonated=False):+ _capture("access_blocked", user_id=user_id)+ return HttpResponseRedirect(ACCOUNT_BLOCKED_LOGIN_URL)+# Deep-link login has no password challenge and no SSO step, so partner-asserted# email ownership is the only thing standing between an attacker and a session.# Require explicit is_email_verified=True - don't trust the legacy None passthroughdiff --git a/ee/partners/stripe/api/provisioning/test/test_deep_links.py b/ee/partners/stripe/api/provisioning/test/test_deep_links.pyindex c9cc75bd892c..22d7b90ff130 100644--- a/ee/partners/stripe/api/provisioning/test/test_deep_links.py+++ b/ee/partners/stripe/api/provisioning/test/test_deep_links.py@@ -77,6 +77,23 @@ class TestDeepLinks(StripeProvisioningTestBase):assert res.status_code == 302assert res["Location"] == f"/verify_email/{self.user.uuid}?reason=stripe_deep_link&email_sent=false"+ def test_blocked_account_lands_on_login_without_a_session(self):+ self.client.logout()+ self._cache_deep_link_token("stripe_blocked_token")+ with patch("ee.partners.stripe.api.provisioning.login.account_refused", return_value=True):+ res = self.client.get(f"{LOGIN_URL}?token=stripe_blocked_token")+ assert res.status_code == 302+ assert res["Location"] == "/login?error_code=access_blocked"+ assert self.client.get("/api/users/@me/").status_code == 401++ def test_deep_link_refused_when_an_access_rule_blocks_the_account(self):+ token = self._get_bearer_token()+ with patch("ee.partners.stripe.api.provisioning.authentication.account_refused", return_value=True):+ res = self._post_signed_with_bearer(DEEP_LINKS_URL, data={"purpose": "dashboard"}, token=token)+ assert res.status_code == 403+ assert res.json()["error"]["code"] == "forbidden"+ assert "access_blocked" in res.json()["error"]["message"]+def test_deep_link_refused_when_the_application_cannot_issue_them(self):self.stripe_app.update_provisioning(can_issue_deep_links=False)token = self._get_bearer_token()diff --git a/ee/vercel/integration.py b/ee/vercel/integration.pyindex 976a7422e4aa..5bc7688cfd55 100644--- a/ee/vercel/integration.py+++ b/ee/vercel/integration.py@@ -18,6 +18,7 @@ from rest_framework import exceptionsfrom two_factor.utils import default_devicefrom posthog.api.signup import SIGNUP_BLOCKED_DETAIL, signup_refused+from posthog.auth import ACCOUNT_BLOCKED_LOGIN_URL, account_refusedfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.dataclasses import frozenfrom posthog.event_usage import report_user_signed_up@@ -66,6 +67,10 @@ class RequiresExistingUserLogin(Exception):super().__init__(f"User {email} must login first")+class SSOLoginRefused(Exception):+ pass++@dataclassclass SSOParams:mode: str@@ -919,6 +924,8 @@ class VercelIntegration:@staticmethoddef _authenticate_and_login_user(request, claims: VercelUserClaims, resource_id: str | None) -> User:user = VercelIntegration._find_sso_user(claims)+ if account_refused(request, user, call_site="vercel_sso", impersonated=False):+ raise SSOLoginRefused()if user.is_email_verified is not True and VercelIntegration._claims_prove_email(claims, user.email):# Vercel verified the mailbox before issuing the claim, so this login proves it.user.is_email_verified = True@@ -1106,6 +1113,8 @@ class VercelIntegration:integration="vercel",)return login_url+ except SSOLoginRefused:+ return ACCOUNT_BLOCKED_LOGIN_URLexcept Exception as e:logger.exception("Vercel SSO authentication failed", error=str(e), integration="vercel")capture_exception(e)diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 03e351df1b8d..7129ff741973 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -95,6 +95,9 @@ export function isScopeNotFoundError(error: unknown): boolean {return typeof detail === 'string' && SCOPE_NOT_FOUND_DETAILS.has(detail)}+/** DRF code of a security access rule refusal (products/security). Keep in sync with the backend. */+export const ACCESS_BLOCKED_ERROR_CODE = 'access_blocked'+/** The 403 gates `apiStatusLogic` recovers from, keyed by the DRF `code` the backend sends. */const HANDLED_AUTH_GATE_CODES: ReadonlySet<string> = new Set(['two_factor_setup_required',diff --git a/frontend/src/lib/logic/apiStatusLogic.test.ts b/frontend/src/lib/logic/apiStatusLogic.test.tsindex 8c6741c1aa86..d376d4a768bc 100644--- a/frontend/src/lib/logic/apiStatusLogic.test.ts+++ b/frontend/src/lib/logic/apiStatusLogic.test.ts@@ -53,12 +53,20 @@ describe('apiStatusLogic', () => {logoutSpy.mockRestore()})- it('triggers auto-logout on 401 for non-impersonated users', async () => {+ it.each([+ ['an expired session', {}, undefined],+ ['an access rule refusal', { code: 'access_blocked' }, 'access_blocked'],+ ])('triggers auto-logout on 401 for non-impersonated users, for %s', async (_, body, reason) => {// The real logout listener submits a <form>, which jsdom doesn't implement- const submitSpy = jest.spyOn(HTMLFormElement.prototype, 'submit').mockImplementation()+ let submitted: HTMLFormElement | undefined+ const submitSpy = jest+ .spyOn(HTMLFormElement.prototype, 'submit')+ .mockImplementation(function (this: HTMLFormElement) {+ submitted = this+ })useMocks({get: {- '/api/users/@me/': () => [401, {}],+ '/api/users/@me/': () => [401, body],},})initKeaTests()@@ -76,7 +84,9 @@ describe('apiStatusLogic', () => {logic.actions.onApiResponse(mockResponse)}).toFinishAllListeners()- expect(logoutSpy).toHaveBeenCalled()+ expect(logoutSpy).toHaveBeenCalledWith(true, undefined, reason)+ // The /logout view turns the reason into the message the login page shows.+ expect((submitted?.elements.namedItem('reason') as HTMLInputElement | null)?.value).toBe(reason)logoutSpy.mockRestore()submitSpy.mockRestore()})diff --git a/frontend/src/lib/logic/apiStatusLogic.ts b/frontend/src/lib/logic/apiStatusLogic.tsindex 52e989bd2a3f..9f5e3e537cdb 100644--- a/frontend/src/lib/logic/apiStatusLogic.ts+++ b/frontend/src/lib/logic/apiStatusLogic.ts@@ -4,6 +4,7 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { ACCESS_BLOCKED_ERROR_CODE } from 'lib/api-error'import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'import { userLogic } from 'scenes/userLogic'@@ -231,7 +232,10 @@ export const apiStatusLogic = kea<apiStatusLogicType>([// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersRetrieve() from '~/generated/core/api' instead.await api.get('api/users/@me/').catch((error: any) => {if (error.status === 401) {- userLogic.findMounted()?.actions.logout(true)+ // An access rule refusal is not an expired session, so the person is told why.+ const reason =+ error.code === ACCESS_BLOCKED_ERROR_CODE ? ACCESS_BLOCKED_ERROR_CODE : undefined+ userLogic.findMounted()?.actions.logout(true, undefined, reason)}})}diff --git a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsxindex 58a1e76f254a..8a818984b681 100644--- a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx+++ b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx@@ -40,4 +40,6 @@ export const ERROR_MESSAGES: Record<string, string | JSX.Element> = {invalid_invite:'This invite link is no longer valid. It may have expired or been revoked. Please ask your administrator for a new invite.',social_login_failure: 'Login failed. Please try again or contact your administrator.',+ access_blocked:+ "We couldn't sign you in. If you think this is a mistake, contact support and quote the code access_blocked.",}diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex d46b6d0923ea..694f40932ddc 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -168,10 +168,12 @@ export interface userLogicActions {}logout: (preserveLocation?: any,- nextUrl?: string+ nextUrl?: string,+ reason?: string) => {nextUrl: string | undefinedpreserveLocation: any+ reason: string | undefined}resetUserDetails: (values?: Record<string, any>) => {values?: Record<string, any>@@ -433,7 +435,11 @@ export const userLogic = kea<userLogicType>([actions(() => ({loadUser: (resetOnFailure?: boolean) => ({ resetOnFailure }),updateCurrentOrganization: (organizationId: string, destination?: string) => ({ organizationId, destination }),- logout: (preserveLocation = false, nextUrl?: string) => ({ preserveLocation, nextUrl }),+ logout: (preserveLocation = false, nextUrl?: string, reason?: string) => ({+ preserveLocation,+ nextUrl,+ reason,+ }),upgradeImpersonation: (reason: string) => ({ reason }),updateUser: (user: Partial<UserType>, successCallback?: () => void, failureCallback?: () => void) => ({user,@@ -648,7 +654,7 @@ export const userLogic = kea<userLogicType>([],}),listeners(({ actions, values, cache }) => ({- logout: ({ preserveLocation, nextUrl }) => {+ logout: ({ preserveLocation, nextUrl, reason }) => {if (cache.loggingOut) {return}@@ -677,6 +683,15 @@ export const userLogic = kea<userLogicType>([csrfInput.value = getCookie('posthog_csrftoken') || ''form.appendChild(csrfInput)+ // The server turns a known reason into the message the login page shows.+ if (reason) {+ const reasonInput = document.createElement('input')+ reasonInput.type = 'hidden'+ reasonInput.name = 'reason'+ reasonInput.value = reason+ form.appendChild(reasonInput)+ }+if (preserveLocation || nextUrl) {const { pathname, search, hash } = window.locationconst nextInput = document.createElement('input')diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 365186f1d713..0cfab1428527 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -35,7 +35,7 @@ from django_otp.plugins.otp_static.models import StaticDevicefrom drf_spectacular.utils import extend_schemafrom loginas.utils import is_impersonated_session, restore_original_loginfrom requests import RequestException-from rest_framework import mixins, permissions, serializers, status, viewsets+from rest_framework import exceptions, mixins, permissions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import APIExceptionfrom rest_framework.request import Request@@ -54,6 +54,7 @@ from webauthn.helpers import base64url_to_bytes, bytes_to_base64url, options_to_from webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredentialDescriptorfrom posthog.api.email_verification import email_verification_code_verifier, is_email_verification_disabled+from posthog.auth import ACCOUNT_BLOCKED_DETAILfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMESfrom posthog.email import is_email_available@@ -105,7 +106,10 @@ from posthog.utils import ()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.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 SecuritySurface@@ -133,6 +137,10 @@ def sso_enforcement_for_login_address(email: str, user: User | None) -> str | Noreturn OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email)+# Reasons a logout can pass to the login page, which holds the copy for each one.+_LOGOUT_REASONS = frozenset({SECURITY_REFUSAL_CODE})++@require_http_methods(["POST"])def logout(request):clear_two_factor_session_flags(request)@@ -146,6 +154,10 @@ def logout(request):auth_logout(request)+ reason = request.POST.get("reason", "")+ if reason in _LOGOUT_REASONS:+ return redirect(f"{settings.LOGIN_URL}?{urlencode({'error_code': reason})}")+next_url = request.POST.get("next")if next_url and url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}):return redirect_to_login(next_url, login_url=settings.LOGIN_URL)@@ -391,13 +403,16 @@ class LoginSerializer(serializers.Serializer):raise serializers.ValidationError("Invalid email or password.", code="invalid_credentials")try:- security_shadow_check(+ refused = security_access_refused(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")+ logger.exception("security_access_check_site_failed", call_site="login")+ refused = False+ if refused:+ raise exceptions.PermissionDenied(ACCOUNT_BLOCKED_DETAIL, code=SECURITY_REFUSAL_CODE)if not is_email_verified_for_login(user):# A fresh code was just emailed; hand the frontend the uuid so it can route to@@ -1470,6 +1485,27 @@ def social_reauth(raise AuthFailed(backend, "reauth_user_mismatch")+def social_access_rules_allow(+ strategy: DjangoStrategy, backend: BaseAuth, user: User | None = None, **kwargs: Any+) -> None:+ """Refuse an SSO login for an account that an enforced access rule blocks, before a session starts."""+ if user is None:+ # A new account is checked where it is created: the signup serializer, or the SSO invite+ # and verified-domain joins in posthog/api/signup.py.+ return+ try:+ refused = security_access_refused(+ SecuritySubject(email=user.email, user_uuid=str(user.uuid), ip=get_trusted_client_ip(strategy.request)),+ SecuritySurface.APP,+ call_site="sso_login",+ )+ except Exception:+ logger.exception("security_access_check_site_failed", call_site="sso_login")+ refused = False+ if refused:+ raise AuthFailed(backend, SECURITY_REFUSAL_CODE)++def social_reauth_complete(strategy: DjangoStrategy, backend, user: User | None = None, **kwargs) -> None:"""Grant the step-up, once every other pipeline step has accepted the flow.diff --git a/posthog/api/livestream.py b/posthog/api/livestream.pyindex 3e6539dd56e9..59eb93ec1779 100644--- a/posthog/api/livestream.py+++ b/posthog/api/livestream.py@@ -10,6 +10,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.views import APIView+from posthog.auth import refuse_blocked_accountfrom posthog.jwt import PosthogJwtAudience, decode_jwtfrom posthog.models import OrganizationMembership, Team, Userfrom posthog.models.activity_logging.utils import ActivityCredentialMixin@@ -43,6 +44,8 @@ class LivestreamAuthentication(ActivityCredentialMixin, BaseAuthentication):)except (jwt.PyJWTError, KeyError, TypeError, ValueError, User.DoesNotExist, Team.DoesNotExist):raise AuthenticationFailed("Invalid live stream token.")+ # The livestream service re-checks every stream here, so a blocked account's 7-day token stops working.+ refuse_blocked_account(request, user, call_site="livestream", impersonated=False)self.record_activity_actor(user)return user, teamdiff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 489746fe377e..5e2d5b6553be 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -17,7 +17,7 @@ from django.core import mailfrom django.core.asgi import get_asgi_applicationfrom django.core.cache import cachefrom django.db import connection-from django.http import HttpResponse+from django.http import HttpRequest, HttpResponsefrom django.test import RequestFactory, SimpleTestCase, override_settingsfrom django.test.utils import CaptureQueriesContextfrom django.utils import timezone@@ -39,7 +39,9 @@ from two_factor.utils import totp_digitsfrom posthog.api.authentication import password_reset_token_generator, social_login_notificationfrom posthog.api.email_verification import is_email_verification_disabledfrom posthog.auth import (+ ExportRendererAuthentication,InternalAPIUser,+ JwtAuthentication,OAuthAccessTokenAuthentication,PersonalAPIKeyAuthentication,ProjectSecretAPIKeyAuthentication,@@ -49,6 +51,7 @@ from posthog.auth import (TeamSecretTokenUser,WidgetAuthentication,_extract_phs_token,+ mint_export_renderer_token,)from posthog.clickhouse.query_tagging import AccessMethod, get_query_tags, tags_contextfrom posthog.helpers.user_devices import (@@ -56,6 +59,7 @@ from posthog.helpers.user_devices import (build_known_device_cookie_value,has_valid_known_device_cookie,)+from posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.middleware import KnownLoginDeviceCookieMiddlewarefrom posthog.models import Userfrom posthog.models.activity_logging.signal_handlers import post_login@@ -69,6 +73,7 @@ from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.feature_flags.backend.models.feature_flag import FeatureFlagVALID_TEST_PASSWORD = "mighty-strong-secure-1337!!"@@ -838,16 +843,59 @@ class TestDevLoginAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+class TestInternalTokensRefuseBlockedAccounts(APIBaseTest):+ def _authenticator_and_request(+ self, kind: str+ ) -> tuple[ExportRendererAuthentication | JwtAuthentication, HttpRequest]:+ if kind == "export_renderer":+ asset = ExportedAsset.objects.create(+ team=self.team,+ created_by=self.user,+ export_format=ExportedAsset.ExportFormat.PNG,+ export_context={"session_recording_id": "recording-id"},+ )+ token = mint_export_renderer_token(+ user_id=self.user.id, team_id=self.team.id, exported_asset_id=asset.id, scope="session_recording:read"+ )+ authenticator: ExportRendererAuthentication | JwtAuthentication = ExportRendererAuthentication()+ else:+ token = encode_jwt({"id": self.user.id}, timedelta(minutes=5), PosthogJwtAudience.IMPERSONATED_USER)+ authenticator = JwtAuthentication()+ return authenticator, APIRequestFactory().get("/", headers={"authorization": f"Bearer {token}"})++ @parameterized.expand([("export renderer token", "export_renderer"), ("internal JWT", "jwt")])+ def test_a_refused_account_keeps_the_refusal_code(self, _name: str, kind: str) -> None:+ # Both authenticators wrap their body in a catch-all that would turn the refusal into "Token invalid."+ authenticator, request = self._authenticator_and_request(kind)++ with patch("posthog.auth.security_access_refused", return_value=True):+ with pytest.raises(AuthenticationFailed) as raised:+ authenticator.authenticate(request)+ assert raised.value.get_codes() == "access_blocked"++ with patch("posthog.auth.security_access_refused", return_value=False):+ result = authenticator.authenticate(request)+ assert result is not None and result[0] == self.user++class TestLogoutRedirect(APIBaseTest):"""Tests that /logout preserves a safe `next` param so users return to where they wereafter logging back in."""- def test_logout_without_next_redirects_to_login(self):- response = self.client.post("/logout")+ @parameterized.expand(+ [+ ("no reason", {}, None),+ ("an unknown reason", {"reason": "Your account was hacked, call this number"}, None),+ ("an access rule refusal", {"reason": "access_blocked"}, "access_blocked"),+ ]+ )+ def test_logout_without_next_redirects_to_login(self, _name, data, error_code):+ response = self.client.post("/logout", data, format="multipart")self.assertEqual(response.status_code, status.HTTP_302_FOUND)- self.assertEqual(response["Location"], settings.LOGIN_URL)+ expected = settings.LOGIN_URL if error_code is None else f"{settings.LOGIN_URL}?error_code={error_code}"+ self.assertEqual(response["Location"], expected)def test_logout_forwards_safe_next_param(self):response = self.client.post("/logout", {"next": "/settings/user-notifications"}, format="multipart")diff --git a/posthog/api/test/test_livestream.py b/posthog/api/test/test_livestream.pyindex eb454b217cd3..cd482a2e39f3 100644--- a/posthog/api/test/test_livestream.py+++ b/posthog/api/test/test_livestream.py@@ -1,6 +1,7 @@from datetime import timedeltafrom posthog.test.base import APIBaseTest+from unittest.mock import patchfrom django.utils import timezone@@ -86,3 +87,9 @@ class TestLivestreamAuthorization(APIBaseTest):self.assertEqual(self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=authorization).status_code, 401)++ def test_refuses_an_account_an_access_rule_blocks(self) -> None:+ with patch("posthog.auth.security_access_refused", return_value=True):+ response = self.client.get("/api/livestream/authorize/", HTTP_AUTHORIZATION=f"Bearer {self._token()}")+ self.assertEqual(response.status_code, 401)+ self.assertEqual(response.json()["code"], "access_blocked")diff --git a/posthog/api/test/test_webauthn.py b/posthog/api/test/test_webauthn.pyindex 0ba8d0b86141..8b9978ae5c74 100644--- a/posthog/api/test/test_webauthn.py+++ b/posthog/api/test/test_webauthn.py@@ -10,8 +10,10 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import AuthenticationFailed+from webauthn.helpers import bytes_to_base64url-from posthog.api.webauthn import WEBAUTHN_REGISTRATION_CHALLENGE_KEY, WebAuthnLoginViewSet+from posthog.api.webauthn import WEBAUTHN_REGISTRATION_CHALLENGE_KEY, WebAuthnLoginViewSet, user_uuid_to_handlefrom posthog.models import Organization, Userfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig@@ -254,6 +256,37 @@ class TestWebAuthnLogin(APIBaseTest):self.assertEqual(me_response.status_code, status.HTTP_200_OK)self.assertEqual(me_response.json()["email"], self.user.email)+ @patch(+ "posthog.api.webauthn.refuse_blocked_account",+ side_effect=AuthenticationFailed("We couldn't sign you in.", code="access_blocked"),+ )+ @patch("posthog.auth.verify_passkey_authentication_response")+ def test_login_complete_is_refused_by_an_access_rule(self, mock_verify, _refuse):+ self.client.logout()+ self.client.post("/api/webauthn/login/begin/")+ mock_verify.return_value = MagicMock(new_sign_count=1)++ response = self.client.post(+ "/api/webauthn/login/complete/",+ {+ "id": bytes_to_base64url(self.credential.credential_id),+ "rawId": bytes_to_base64url(self.credential.credential_id),+ "type": "public-key",+ "response": {+ "authenticatorData": "data",+ "clientDataJSON": "data",+ "signature": "sig",+ "userHandle": bytes_to_base64url(user_uuid_to_handle(self.user.uuid)),+ },+ },+ format="json",+ )++ # The view's catch-all would turn the refusal into a generic 400 and hide its code.+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)+ self.assertEqual(response.json()["code"], "access_blocked")+ self.assertEqual(self.client.get("/api/users/@me/").status_code, status.HTTP_401_UNAUTHORIZED)+@patch("posthog.api.authentication.is_email_available", return_value=True)@patch("posthog.api.authentication.email_verification_code_verifier.send_code")@patch("posthog.auth.verify_passkey_authentication_response")diff --git a/posthog/api/webauthn.py b/posthog/api/webauthn.pyindex 4610a7279310..8497065015fe 100644--- a/posthog/api/webauthn.py+++ b/posthog/api/webauthn.py@@ -11,6 +11,7 @@ from axes.exceptions import AxesBackendPermissionDeniedfrom axes.handlers.proxy import AxesProxyHandlerfrom rest_framework import permissions, serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import AuthenticationFailedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom webauthn.helpers import base64url_to_bytes, bytes_to_base64url, options_to_json@@ -18,7 +19,7 @@ from webauthn.helpers.decode_credential_public_key import decode_credential_publfrom webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredentialDescriptorfrom posthog.api.authentication import EmailVerificationPending, axes_locked_out, is_email_verified_for_login-from posthog.auth import SessionAuthentication, WebAuthnAuthenticationResponse, WebauthnBackend+from posthog.auth import SessionAuthentication, WebAuthnAuthenticationResponse, WebauthnBackend, refuse_blocked_accountfrom posthog.event_usage import report_user_logged_infrom posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.helpers.two_factor_session import set_two_factor_verified_in_session@@ -282,6 +283,8 @@ class WebAuthnLoginViewSet(viewsets.ViewSet):if policy_response := self._enforce_login_policy(request, verified_user):return policy_response+ refuse_blocked_account(request, verified_user, call_site="passkey_login", impersonated=False)+# Login the user with the WebauthnBackendlogin(request, verified_user, backend="posthog.auth.WebauthnBackend")@@ -301,6 +304,8 @@ class WebAuthnLoginViewSet(viewsets.ViewSet):# The DRF handler formats this as a 401 with the user uuid, the same# response as the password login path.raise+ except AuthenticationFailed:+ raiseexcept Exception as e:logger.exception("webauthn_login_error", error=str(e))return Response(diff --git a/posthog/auth.py b/posthog/auth.pyindex 9348cd0d2f86..e1b61f37fa2b 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -6,7 +6,7 @@ import functoolsfrom abc import abstractmethodfrom datetime import timedeltafrom typing import TYPE_CHECKING, Any, ClassVar, Optional, TypedDict, Union-from urllib.parse import parse_qs, urlparse+from urllib.parse import parse_qs, urlencode, urlparsefrom django.apps import appsfrom django.conf import settings@@ -20,6 +20,7 @@ from django.utils import timezoneimport jwtimport structlogimport posthoganalytics+from loginas.utils import is_impersonated_sessionfrom opentelemetry import tracefrom prometheus_client import Counterfrom rest_framework import authentication@@ -69,7 +70,10 @@ 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.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 SecuritySurfacefrom products.signals.backend.facade.activity_client import resolve_scout_client_tag@@ -102,6 +106,47 @@ PERSONAL_API_KEY_QUERY_PARAM_COUNTER = Counter(AUTH_BRAND_COOKIE = "ph_auth_brand"+# Shown at login and on every request once a block rule refuses the account. It says nothing+# about the rule that matched; the code is what lets support trace it to an access rule.+ACCOUNT_BLOCKED_DETAIL = (+ "We couldn't sign you in. If you think this is a mistake, contact support "+ f"and quote the code {SECURITY_REFUSAL_CODE}."+)+# The login page explains a refusal from this error code, so a passwordless login that refuses+# an account redirects here.+ACCOUNT_BLOCKED_LOGIN_URL = f"{settings.LOGIN_URL}?{urlencode({'error_code': SECURITY_REFUSAL_CODE})}"+++def account_refused(request: Union[HttpRequest, Request], user: User, *, call_site: str, impersonated: bool) -> bool:+ """Whether an enforced access rule blocks this account on the app surface. Never raises.++ Every authenticator that resolves a user asks this, because DRF stops at the first one that+ succeeds, so a check in one of them alone leaves the others open. An impersonated request is+ never refused, so staff can investigate a blocked account; its match counts as a would-block.+ """+ try:+ return security_access_refused(+ SecuritySubject(+ email=user.email,+ user_uuid=str(user.uuid),+ ip=get_trusted_client_ip(getattr(request, "_request", request)),+ ),+ SecuritySurface.APP,+ call_site=call_site,+ enforce=not impersonated,+ )+ except Exception:+ structlog_logger.exception("security_access_check_site_failed", call_site=call_site)+ return False+++def refuse_blocked_account(+ request: Union[HttpRequest, Request], user: User, *, call_site: str, impersonated: bool+) -> None:+ """Raise when an enforced access rule blocks this account on the app surface."""+ if account_refused(request, user, call_site=call_site, impersonated=impersonated):+ raise AuthenticationFailed(ACCOUNT_BLOCKED_DETAIL, code=SECURITY_REFUSAL_CODE)+def get_auth_brand_for_client_id(client_id: str | None) -> str | None:if not client_id:@@ -200,18 +245,7 @@ class 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")+ refuse_blocked_account(request, user, call_site="session", impersonated=is_impersonated_session(request))return (user, auth)@@ -354,6 +388,9 @@ class PersonalAPIKeyAuthentication(ActivityCredentialMixin, authentication.BaseApersonal_api_key_object.last_used_at = nowpersonal_api_key_object.save(update_fields=["last_used_at"])assert personal_api_key_object.user is not None+ refuse_blocked_account(+ request, personal_api_key_object.user, call_site="personal_api_key", impersonated=False+ )# :KLUDGE: CHMiddleware does not receive the correct user when authenticating by api key.tag_authentication(@@ -544,6 +581,7 @@ class JwtAuthentication(ActivityCredentialMixin, authentication.BaseAuthenticatitoken = authorization_match.group(1).strip()info = decode_jwt(token, PosthogJwtAudience.IMPERSONATED_USER)user = User.objects.get(pk=info["id"])+ refuse_blocked_account(request, user, call_site="jwt", impersonated=False)self.record_activity_actor(user)return (user, None)except AuthenticationFailed:@@ -729,6 +767,7 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Basif not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):raise AuthenticationFailed(detail="ID-JAG (XAA) is not enabled for this organization.")+ refuse_blocked_account(request, user, call_site="id_jag_token", impersonated=False)self.id_jag_claims = claimsself.scopes = str(claims.get("scope") or "").split()self.organization_id = organization_id@@ -810,12 +849,14 @@ class ExportRendererAuthentication(ActivityCredentialMixin, authentication.BaseAself.exported_asset_id = exported_asset_idself.export_context = export_contextuser = User.objects.get(pk=user_id)- self.record_activity_actor(user, str(exported_asset_id))- return user, Noneexcept (jwt.DecodeError, jwt.InvalidAudienceError):return Noneexcept Exception:raise AuthenticationFailed(detail="Token invalid.")+ # Outside the try, so the refusal keeps its code instead of becoming "Token invalid."+ refuse_blocked_account(request, user, call_site="export_renderer", impersonated=False)+ self.record_activity_actor(user, str(exported_asset_id))+ return user, Nonedef authenticate_header(self, request) -> str:return self.keyword@@ -1012,6 +1053,9 @@ class OAuthAccessTokenAuthentication(ActivityCredentialMixin, authentication.Basuser = access_token.userif user is None:raise AuthenticationFailed(detail="User associated with access token not found.")+ refuse_blocked_account(+ request, user, call_site="oauth_token", impersonated=access_token.impersonated_by_id is not None+ )tag_authentication(user_id=user.pk,@@ -1155,6 +1199,7 @@ class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):except (KeyError, PersonalAPIKey.DoesNotExist) as error:raise AuthenticationFailed(detail="Source personal API key is no longer valid.") from error+ refuse_blocked_account(request, personal_api_key.user, call_site="personal_api_key", impersonated=False)self.personal_api_key = personal_api_keytag_authentication(user_id=personal_api_key.user.pk,diff --git a/posthog/middleware.py b/posthog/middleware.pyindex ecff5932a21e..d14fde5e91e6 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -1393,6 +1393,7 @@ class SocialAuthExceptionMiddleware:"gitlab_sso_enforced","sso_enforced","reauth_user_mismatch",+ "access_blocked",):return redirect(sso_failure_redirect_url(request, error))diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 19f86f6c9501..78cff26c7fe2 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -318,6 +318,9 @@ SOCIAL_AUTH_PIPELINE = (# Must stay ahead of associate_by_email, which links an existing account by email with no check of its own"posthog.api.authentication.social_email_verified_by_provider","social_core.pipeline.social_auth.associate_by_email",+ # Must stay ahead of the end of the pipeline, where the session starts, and after the steps+ # that resolve the existing account+ "posthog.api.authentication.social_access_rules_allow","posthog.api.signup.social_create_user","social_core.pipeline.social_auth.associate_user","social_core.pipeline.social_auth.load_extra_data",diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 935b81850490..5d0e168a3529 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -2376,6 +2376,12 @@ class TestSocialAuthExceptionMiddleware(APIBaseTest):AuthFailed(_social_auth_backend(), "sso_enforced"),"/login?error_code=sso_enforced",),+ (+ "access_blocked",+ "/complete/google-oauth2/",+ AuthFailed(_social_auth_backend(), "access_blocked"),+ "/login?error_code=access_blocked",+ ),])def test_redirects_with_expected_url(self, _name, path, exception, expected_url):diff --git a/products/security/backend/facade/api.py b/products/security/backend/facade/api.pyindex 8e9b9b8f2cf7..3f4a86f4252e 100644--- a/products/security/backend/facade/api.py+++ b/products/security/backend/facade/api.py@@ -102,10 +102,12 @@ def _record_block()-def access_refused(subject: contracts.SubjectInput, surface: Surface, *, call_site: str) -> bool:+def access_refused(subject: contracts.SubjectInput, surface: Surface, *, call_site: str, enforce: bool = True) -> 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.+ `enforce=False` does the same on an enforced surface, for a request that must get through,+ such as staff impersonating the account.Never raises: a failed decision refuses nobody, so a broken check turns the blocklist offinstead of locking everyone out. The error counter is what shows that it happened."""@@ -113,7 +115,7 @@ def access_refused(subject: contracts.SubjectInput, surface: Surface, *, call_sidecision = _counted(decide(subject, surface), call_site)if decision.outcome != Outcome.BLOCK:return False- refused = _is_enforced(surface)+ refused = enforce and _is_enforced(surface)_record_block(decision, subject, call_site, refused=refused)return refusedexcept Exception:@@ -122,18 +124,6 @@ def access_refused(subject: contracts.SubjectInput, surface: Surface, *, call_sireturn 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- _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.diff --git a/products/security/backend/tests/test_shadow_call_sites.py b/products/security/backend/tests/test_block_call_sites.pysimilarity index 53%rename from products/security/backend/tests/test_shadow_call_sites.pyrename to products/security/backend/tests/test_block_call_sites.pyindex ddb226eba231..ac6f47f31999 100644--- a/products/security/backend/tests/test_shadow_call_sites.py+++ b/products/security/backend/tests/test_block_call_sites.py@@ -1,7 +1,12 @@+import time+from datetime import timedelta+import pytest+import time_machinefrom posthog.test.base import APIBaseTest-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patch+from django.conf import settingsfrom django.test import RequestFactoryfrom django.utils import timezone@@ -9,15 +14,20 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom social_core.exceptions import AuthFailed+from posthog.api.authentication import social_access_rules_allowfrom 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.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization_domain import OrganizationDomainfrom posthog.models.organization_invite import OrganizationInvite+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value+from products.security.backend.logic import snapshotfrom products.security.backend.tests.helpers import block_rule, enforcing, seed_rules@@ -31,7 +41,7 @@ def _count(surface: str, call_site: str, target_type: str) -> float:)-class TestShadowCallSites(APIBaseTest):+class TestBlockCallSites(APIBaseTest):# The default test user is a posthog.com account, which no block rule may reach.CONFIG_EMAIL = "[email protected]"@@ -59,16 +69,21 @@ class TestShadowCallSites(APIBaseTest):if status == 403:assert response.json()["code"] == "access_blocked"- def test_blocked_login_is_logged_and_still_succeeds(self) -> None:+ @parameterized.expand([("logged only", [], 200, 1), ("enforced", ["app"], 403, 0)])+ def test_blocked_login(self, _name: str, enforced: list[str], status: int, would_block: int) -> 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+ with enforcing(*enforced):+ response = self.client.post(+ "/api/login", {"email": "[email protected]", "password": "a-long-password-123"}+ )+ assert response.status_code == status, response.json()+ assert _count("app", "login", "user_uuid") == before + would_block+ assert ("_auth_user_id" in self.client.session) is (status == 200)+ if status == 403:+ assert response.json()["code"] == "access_blocked"@parameterized.expand([("logged only", [], 201, 1), ("enforced", ["signup"], 403, 0)])def test_blocked_existing_user_accepting_an_invite(@@ -87,12 +102,110 @@ class TestShadowCallSites(APIBaseTest):assert _count("signup", "invite_signup", "email") == before + would_blockassert self.user.organizations.filter(id=new_org.id).exists() is (status == 201)- def test_blocked_session_is_logged_and_still_served(self) -> None:+ @parameterized.expand([("logged only", [], False), ("enforced", ["app"], True)])+ def test_blocked_sso_login(self, _name: str, enforced: list[str], refused: bool) -> None:+ user = User.objects.create_and_join(self.organization, "[email protected]", None)+ seed_rules(block_rule(targetValue="[email protected]"))+ before = _count("app", "sso_login", "email")+ strategy = MagicMock(request=RequestFactory().get("/complete/google-oauth2/"))++ with enforcing(*enforced):+ if refused:+ with pytest.raises(AuthFailed, match="access_blocked"):+ social_access_rules_allow(strategy, MagicMock(), user=user)+ else:+ social_access_rules_allow(strategy, MagicMock(), user=user)++ assert _count("app", "sso_login", "email") == before + (0 if refused else 1)+ # The step does nothing unless the pipeline runs it before the session starts.+ pipeline = list(settings.SOCIAL_AUTH_PIPELINE)+ assert pipeline.index("posthog.api.authentication.social_access_rules_allow") < pipeline.index(+ "posthog.api.signup.social_create_user"+ )++ @parameterized.expand(+ [+ ("logged only", [], False, 200, 1),+ ("enforced", ["app"], False, 401, 0),+ ("enforced, but staff are impersonating", ["app"], True, 200, 1),+ ]+ )+ def test_blocked_session(+ self, _name: str, enforced: list[str], impersonated: bool, status: int, would_block: int+ ) -> 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+ with (+ enforcing(*enforced),+ patch("posthog.auth.is_impersonated_session", return_value=impersonated),+ ):+ response = self.client.get("/api/users/@me/")+ assert response.status_code == status, response.json()+ assert _count("app", "session", "email") == before + would_block+ if status == 401:+ assert response.json()["code"] == "access_blocked"++ def _bearer(self, kind: str) -> str:+ if kind == "personal_api_key":+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="Test", user=self.user, secure_value=hash_key_value(key), scopes=["*"])+ return key+ application = OAuthApplication.objects.create(+ name="Test app",+ client_id="test_client_id",+ client_secret="test_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",+ )+ token = f"pha_{generate_random_token_personal()}"+ OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=token,+ scope="*",+ expires=timezone.now() + timedelta(hours=1),+ )+ return token++ @parameterized.expand(+ [+ ("personal API key, logged only", "personal_api_key", [], 200, 1),+ ("personal API key, enforced", "personal_api_key", ["app"], 401, 0),+ ("OAuth token, logged only", "oauth_token", [], 200, 1),+ ("OAuth token, enforced", "oauth_token", ["app"], 401, 0),+ ]+ )+ def test_blocked_bearer_credential(+ self, _name: str, kind: str, enforced: list[str], status: int, would_block: int+ ) -> None:+ # DRF stops at the first authenticator that succeeds, and the bearer ones run before the+ # session one, so a check on the session alone leaves an existing key or token working.+ seed_rules(block_rule(targetType="email", targetValue=self.user.email.lower()))+ token = self._bearer(kind)+ self.client.logout()+ before = _count("app", kind, "email")++ with enforcing(*enforced):+ response = self.client.get("/api/users/@me/", headers={"authorization": f"Bearer {token}"})++ assert response.status_code == status, response.json()+ assert _count("app", kind, "email") == before + would_block+ if status == 401:+ assert response.json()["code"] == "access_blocked"++ def test_session_check_reads_the_memo_not_redis(self) -> None:+ # The session check runs on every authenticated request, so a Redis read here would be+ # a latency incident on the whole app.+ seed_rules(block_rule(targetValue="[email protected]"))+ with enforcing("app"), time_machine.travel(time.time(), tick=False):+ assert self.client.get("/api/users/@me/").status_code == 200+ with patch.object(snapshot, "get_client") as redis:+ assert self.client.get("/api/users/@me/").status_code == 200+ redis.assert_not_called()def test_unmatched_requests_log_nothing(self) -> None:seed_rules(block_rule(targetValue="[email protected]"))diff --git a/products/security/backend/tests/test_facade.py b/products/security/backend/tests/test_facade.pyindex 6437e65884e0..41d83db495ce 100644--- a/products/security/backend/tests/test_facade.py+++ b/products/security/backend/tests/test_facade.py@@ -13,7 +13,6 @@ from products.security.backend.facade.api import (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@@ -82,12 +81,12 @@ class TestFacade(BaseTest):with patch("products.security.backend.facade.api.current_snapshot", side_effect=RuntimeError("boom")):assert is_email_code_exempt("[email protected]") is False- def test_shadow_check_counts_and_never_raises(self) -> None:+ def test_access_refused_counts_every_decision_and_never_raises(self) -> None:user = User.objects.create_and_join(self.organization, "[email protected]", "password1234")seed_rules(block_rule(targetType="user_uuid", targetValue=str(user.uuid)))before = _would_block("test_site")blocked_before = _decisions("app", "test_site", "block")- shadow_check(SubjectInput(email=user.email, user_uuid=str(user.uuid)), Surface.APP, call_site="test_site")+ access_refused(SubjectInput(email=user.email, user_uuid=str(user.uuid)), Surface.APP, call_site="test_site")assert _would_block("test_site") == before + 1assert _decisions("app", "test_site", "block") == blocked_before + 1@@ -95,13 +94,13 @@ class TestFacade(BaseTest):# allow, so a counter that moved only on a block would have no series exactly when# there is nothing to block, which is the case it exists to distinguish.allowed_before = _decisions("app", "test_site", "allow")- shadow_check(SubjectInput(email="[email protected]"), Surface.APP, call_site="test_site")+ access_refused(SubjectInput(email="[email protected]"), Surface.APP, call_site="test_site")assert _decisions("app", "test_site", "allow") == allowed_before + 1# A decision that raised is an error, not an evaluation, and must not be counted twice.allowed_before = _decisions("app", "test_site", "allow")with patch("products.security.backend.facade.api.current_snapshot", side_effect=RuntimeError("boom")):- shadow_check(SubjectInput(email=user.email), Surface.APP, call_site="test_site")+ access_refused(SubjectInput(email=user.email), Surface.APP, call_site="test_site")assert _decisions("app", "test_site", "allow") == allowed_before@parameterized.expand(@@ -115,7 +114,7 @@ class TestFacade(BaseTest):def test_exemption_checks_count_every_decision(self, _name: str, scope: str, surface: str, address: str, outcome: str) -> None:- # The exemption checks do not go through shadow_check, so they need their own count+ # The exemption checks do not go through access_refused, so they need their own count# to show that they ran.seed_rules(exempt_rule(targetValue="[email protected]", scope=scope))check = is_email_code_exempt if surface == "email_code" else is_signup_risk_exempt@@ -125,19 +124,25 @@ class TestFacade(BaseTest):@parameterized.expand([- ("surface enforced", ["app"], True),- ("another surface enforced", ["signup", "ai_gateway"], False),- ("nothing enforced", [], False),+ ("surface enforced", ["app"], True, True),+ ("surface enforced, but this request is exempt", ["app"], False, False),+ ("another surface enforced", ["signup", "ai_gateway"], True, False),+ ("nothing enforced", [], True, False),])- def test_access_refused_only_on_an_enforced_surface(self, _name: str, enforced: list[str], expected: bool) -> None:+ def test_access_refused_only_on_an_enforced_surface(+ self, _name: str, enforced: list[str], enforce: bool, 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"+ SubjectInput(email=user.email, user_uuid=str(user.uuid)),+ Surface.APP,+ call_site="refuse_site",+ enforce=enforce,)assert result is expected