: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): skip the radar check for exempt addresses (#108156)
Yasen040776c76133
diff --git a/posthog/test/test_workos_radar.py b/posthog/test/test_workos_radar.pyindex d23f89fb2d08..086ab0ee2dfe 100644--- a/posthog/test/test_workos_radar.py+++ b/posthog/test/test_workos_radar.py@@ -237,11 +237,13 @@ class TestRadarEventLogging(TestCase):duration_ms=75.0,was_blocked=was_blocked,was_bypassed=was_bypassed,+ bypass_source="rule" if was_bypassed else None,)props = mock_capture.call_args[1]["properties"]assert props["was_blocked"] == was_blockedassert props["was_bypassed"] == was_bypassed+ assert props["bypass_source"] == ("rule" if was_bypassed else None)class TestEvaluateAuthAttempt(TestCase):@@ -384,6 +386,7 @@ class TestEvaluateAuthAttempt(TestCase):log_kwargs = mock_log_event.call_args[1]assert log_kwargs["was_blocked"] is Falseassert log_kwargs["was_bypassed"] is True+ assert log_kwargs["bypass_source"] == "legacy"class TestRadarBypassEmailRedis(TestCase):@@ -663,4 +666,5 @@ class TestChallengeFlow(TestCase):assert result == RadarVerdict.CHALLENGElog_kwargs = mock_log_event.call_args[1]assert log_kwargs["was_bypassed"] is True+ assert log_kwargs["bypass_source"] == "legacy"assert log_kwargs["was_challenged"] is Falsediff --git a/posthog/workos_radar.py b/posthog/workos_radar.pyindex 54a6a17eedac..245216d45355 100644--- a/posthog/workos_radar.py+++ b/posthog/workos_radar.py@@ -5,7 +5,8 @@ This module provides a client for the WorkOS Radar Attempts API to evaluatesignup attempts for potential fraud or bot activity. When Radar returns aBLOCK verdict, the attempt is rejected with a SuspiciousAttemptBlockedexception unless the email is on the Redis bypass list managed via the-admin tool.+admin tool, or a security access rule exempts it from the signup risk+check."""import time@@ -25,6 +26,8 @@ from posthog.redis import get_clientfrom posthog.turnstile import create_challenge_nonce, validate_and_consume_nonce, verify_turnstile_tokenfrom posthog.utils import get_ip_address, get_short_user_agent+from products.security.backend.facade.api import is_signup_risk_exempt+logger = structlog.get_logger(__name__)WORKOS_RADAR_API_URL = "https://api.workos.com/radar/attempts"@@ -107,7 +110,7 @@ def evaluate_auth_attempt(Raises:SuspiciousAttemptBlocked: When verdict is BLOCK and the email is- not in the Redis bypass list.+ not in the Redis bypass list and not exempted by an access rule.ChallengeRequired: When verdict is CHALLENGE and no valid Turnstiletoken was provided."""@@ -142,7 +145,8 @@ def evaluate_auth_attempt(user_agent=short_user_agent,duration_ms=duration_ms,was_blocked=outcome == "block",- was_bypassed=outcome == "bypass",+ was_bypassed=outcome.startswith("bypass"),+ bypass_source=outcome.removeprefix("bypass_") if outcome.startswith("bypass") else None,was_challenged=outcome == "challenge",was_challenge_completed=outcome == "completed",)@@ -190,6 +194,20 @@ def _evaluate_verdict(return verdict, (time.perf_counter() - start_time) * 1000+def _legacy_bypass(email: str) -> bool:+ """The Redis list, read so a Redis failure cannot decide the signup on its own.++ Raising here would 500 the request before the access rules are consulted, so an+ address with a valid exemption would be refused by an outage in the list it does+ not use. Treating the failure as a miss hands the decision to the rule check.+ """+ try:+ return is_radar_bypass_email(email)+ except Exception:+ logger.warning("workos_radar_bypass_list_unavailable", email_hash=_hash_email(email))+ return False++def _decide_outcome(verdict: RadarVerdict,email: str,@@ -197,14 +215,21 @@ def _decide_outcome(challenge_nonce: str,ip_address: str,) -> str:- """Return one of: 'allow', 'block', 'bypass', 'challenge', 'completed'."""+ """Return one of: 'allow', 'block', 'bypass_legacy', 'bypass_rule', 'challenge', 'completed'.++ The two bypass values name the source, because after an incident the event stream has+ to say whether an admin's Redis entry or an access rule let the address through.+ """if turnstile_token and challenge_nonce:nonce_valid = validate_and_consume_nonce(challenge_nonce, email, ip_address)token_valid = nonce_valid and verify_turnstile_token(turnstile_token, ip_address)return "completed" if token_valid else "block"- if verdict in (RadarVerdict.BLOCK, RadarVerdict.CHALLENGE) and is_radar_bypass_email(email):- return "bypass"+ if verdict in (RadarVerdict.BLOCK, RadarVerdict.CHALLENGE):+ if _legacy_bypass(email):+ return "bypass_legacy"+ if is_signup_risk_exempt(email):+ return "bypass_rule"if verdict == RadarVerdict.BLOCK:return "block"@@ -294,6 +319,7 @@ def _log_radar_event(duration_ms: float,was_blocked: bool = False,was_bypassed: bool = False,+ bypass_source: Optional[str] = None,was_challenged: bool = False,was_challenge_completed: bool = False,) -> None:@@ -310,6 +336,7 @@ def _log_radar_event("would_block": verdict == RadarVerdict.BLOCK,"was_blocked": was_blocked,"was_bypassed": was_bypassed,+ "bypass_source": bypass_source,"was_challenged": was_challenged,"was_challenge_completed": was_challenge_completed,"is_error": verdict == RadarVerdict.ERROR,@@ -330,6 +357,7 @@ def _log_radar_event(action=action.value,auth_method=auth_method.value,verdict=verdict.value,+ bypass_source=bypass_source,email_hash=_hash_email(email),duration_ms=round(duration_ms, 2),)diff --git a/products/security/backend/facade/hub.py b/products/security/backend/facade/hub.pyindex 7207ea90e05a..d5a670934f68 100644--- a/products/security/backend/facade/hub.py+++ b/products/security/backend/facade/hub.py@@ -18,6 +18,7 @@ from ..logic.hub_auth import (INTERNAL_PURPOSE as INTERNAL_PURPOSE,claims_allow,)+from ..logic.radar_export import export_radar_bypassesfrom ..metrics import HUB_API_AUTH_COUNTER@@ -37,6 +38,10 @@ def posthog_account_exists(*, user_uuid: str | None = None, organization_id: strreturn has_posthog_account(user_uuid=user_uuid, organization_id=organization_id)+def radar_bypasses() -> list[str]:+ return export_radar_bypasses()++def token_allows(claims: Mapping[str, Any] | None, op: str) -> bool:return claims_allow(claims, op)diff --git a/products/security/backend/logic/decisions.py b/products/security/backend/logic/decisions.pyindex ee71e3334eb9..1523332a7a45 100644--- a/products/security/backend/logic/decisions.py+++ b/products/security/backend/logic/decisions.py@@ -24,6 +24,14 @@ SURFACE_EFFECT: dict[Surface, str] = {Surface.SIGNUP_RISK: "exempt",}+# Target types a surface accepts, where accepting every type would be too broad. The hub+# refuses these combinations when a rule is written; refusing them again here means a+# widening there cannot switch off a protection without a change on this side too. A+# surface absent from this map accepts any target type.+SURFACE_TARGET_TYPES: dict[Surface, frozenset[str]] = {+ Surface.SIGNUP_RISK: frozenset({"email", "email_domain"}),+}+PROTECTED_DOMAIN = "posthog.com"@@ -42,9 +50,11 @@ def deciding_rule(index: RuleIndex, subject: Subject, surface: Surface, now: dat# account. Exemptions still apply to one.if effect == "block" and is_protected_domain(subject.domain):return None+ allowed_targets = SURFACE_TARGET_TYPES.get(surface)for rule in candidates(index, subject):if (rule.effect == effect+ and (allowed_targets is None or rule.target_type in allowed_targets)and surface in SCOPE_SURFACES.get(rule.scope, frozenset())and _is_active(rule, now)and rule_matches(rule, subject)diff --git a/products/security/backend/logic/radar_export.py b/products/security/backend/logic/radar_export.pynew file mode 100644index 000000000000..c54869e7870e--- /dev/null+++ b/products/security/backend/logic/radar_export.py@@ -0,0 +1,9 @@+"""Reads the legacy Redis Radar bypass list for the hub's one-time import. Deleted at cut-over."""++from posthog.redis import get_client+from posthog.workos_radar import WORKOS_RADAR_BYPASS_REDIS_KEY+++def export_radar_bypasses() -> list[str]:+ members = get_client().smembers(WORKOS_RADAR_BYPASS_REDIS_KEY)+ return sorted(m.decode() if isinstance(m, bytes) else str(m) for m in members)diff --git a/products/security/backend/presentation/hub_api.py b/products/security/backend/presentation/hub_api.pyindex c750ead6d7ed..15e507c0a18e 100644--- a/products/security/backend/presentation/hub_api.py+++ b/products/security/backend/presentation/hub_api.py@@ -27,6 +27,7 @@ from ..facade.hub import (count_accounts,count_org_members,posthog_account_exists,+ radar_bypasses,record_call,resolve,token_allows,@@ -39,6 +40,7 @@ from .serializers import (OrgMemberCountResponseSerializer,PosthogMembershipRequestSerializer,PosthogMembershipResponseSerializer,+ RadarBypassExportResponseSerializer,ResolveRequestSerializer,ResolveResponseSerializer,)@@ -141,6 +143,22 @@ class PosthogMembershipView(_HubView):return Response(PosthogMembershipResponseSerializer({"has_posthog_account": found}).data)+class RadarBypassExportView(_HubView):+ op = "radar_bypass:export"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ try:+ emails = radar_bypasses()+ except Exception:+ # A 503 tells the hub to retry the import. A 500 reads as a bug and stops it.+ logger.exception("security_hub_radar_export_failed")+ return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)+ # One call returns every address, so the export leaves a record of who read it.+ logger.info("security_hub_radar_export", count=len(emails))+ return Response(RadarBypassExportResponseSerializer({"emails": emails}).data)++class SyncNowView(_HubView):op = "rules:sync_now"@@ -160,5 +178,6 @@ urlpatterns = [path("count-accounts/", csrf_exempt(CountAccountsView.as_view())),path("org-member-count/", csrf_exempt(OrgMemberCountView.as_view())),path("posthog-membership/", csrf_exempt(PosthogMembershipView.as_view())),+ path("radar-bypass-export/", csrf_exempt(RadarBypassExportView.as_view())),path("sync-now/", csrf_exempt(SyncNowView.as_view())),]diff --git a/products/security/backend/presentation/serializers.py b/products/security/backend/presentation/serializers.pyindex 693fea81f723..6e7ffe006edf 100644--- a/products/security/backend/presentation/serializers.py+++ b/products/security/backend/presentation/serializers.py@@ -68,3 +68,9 @@ class OrgMemberCountResponseSerializer(serializers.Serializer):class PosthogMembershipResponseSerializer(serializers.Serializer):has_posthog_account = serializers.BooleanField(help_text="Whether the target holds a posthog.com account.")+++class RadarBypassExportResponseSerializer(serializers.Serializer):+ emails = serializers.ListField(+ child=serializers.CharField(), help_text="Addresses on the legacy Redis Radar bypass list, lowercase."+ )diff --git a/products/security/backend/tests/test_hub_api.py b/products/security/backend/tests/test_hub_api.pyindex 1714f4d2762a..a0ab4e776e86 100644--- a/products/security/backend/tests/test_hub_api.py+++ b/products/security/backend/tests/test_hub_api.py@@ -12,6 +12,7 @@ from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.models import User+from posthog.workos_radar import add_radar_bypass_email, remove_radar_bypass_emailSECRET = "in-us"SETTINGS = {"SECURITY_HUB_REGION": "us", "SECURITY_HUB_INBOUND_JWT_SECRETS": [SECRET]}@@ -98,6 +99,16 @@ class TestHubApi(BaseTest):response = self.post("count-accounts", {"target_type": "ip", "target_value": "1.2.3.4"}, "accounts:count")assert response.status_code == 400+ def test_radar_export(self) -> None:+ add_radar_bypass_email("[email protected]")+ self.addCleanup(remove_radar_bypass_email, "[email protected]")+ assert self.post("radar-bypass-export", {}, "radar_bypass:export").json() == {"emails": ["[email protected]"]}+ assert self.post("radar-bypass-export", {}, "rules:sync_now").status_code == 403++ @patch("products.security.backend.presentation.hub_api.radar_bypasses", side_effect=RuntimeError("redis down"))+ def test_radar_export_answers_503_when_redis_is_unreachable(self, _bypasses: MagicMock) -> None:+ assert self.post("radar-bypass-export", {}, "radar_bypass:export").status_code == 503+@patch("products.security.backend.presentation.hub_api.start_sync_now")def test_sync_now(self, start: MagicMock) -> None:assert self.post("sync-now", {}, "rules:sync_now").status_code == 202diff --git a/products/security/backend/tests/test_radar_call_site.py b/products/security/backend/tests/test_radar_call_site.pynew file mode 100644index 000000000000..b43a528f542c--- /dev/null+++ b/products/security/backend/tests/test_radar_call_site.py@@ -0,0 +1,50 @@+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.workos_radar import RadarVerdict, _decide_outcome, add_radar_bypass_email, remove_radar_bypass_email++from products.security.backend.tests.helpers import exempt_rule, seed_rules+++class TestRadarCallSite(SimpleTestCase):+ def _bypass(self, email: str) -> None:+ # SimpleTestCase does not flush Redis, so an entry left here reaches the next test.+ add_radar_bypass_email(email)+ self.addCleanup(remove_radar_bypass_email, email)++ @parameterized.expand([(RadarVerdict.BLOCK,), (RadarVerdict.CHALLENGE,)])+ def test_exempt_address_bypasses(self, verdict: RadarVerdict) -> None:+ seed_rules(exempt_rule(targetType="email_domain", targetValue="partner.example", scope="signup_risk"))+ assert _decide_outcome(verdict, "[email protected]", "", "", "93.184.216.1") == "bypass_rule"++ def test_other_addresses_keep_the_verdict(self) -> None:+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"+ assert _decide_outcome(RadarVerdict.ALLOW, "[email protected]", "", "", "93.184.216.1") == "allow"++ def test_email_code_exemption_does_not_bypass_radar(self) -> None:+ seed_rules(exempt_rule(targetValue="[email protected]"))+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"++ def test_legacy_redis_bypass_still_works(self) -> None:+ seed_rules()+ self._bypass("[email protected]")+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "bypass_legacy"++ def test_the_legacy_list_wins_the_label_when_both_match(self) -> None:+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))+ self._bypass("[email protected]")+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "bypass_legacy"++ def test_a_target_type_the_hub_forbids_does_not_exempt(self) -> None:+ seed_rules(exempt_rule(targetType="everyone", targetValue="", scope="signup_risk"))+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"++ @patch("posthog.workos_radar.is_radar_bypass_email", side_effect=RuntimeError("redis down"))+ def test_an_unreadable_legacy_list_still_lets_a_rule_decide(self, _bypass: object) -> None:+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "bypass_rule"+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"