Skip to content

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

chore(security): remove the redis radar bypass list (#109770)

Yasen6e762b64a651
diff --git a/ee/api/test/test_admin_oauth2_middleware.py b/ee/api/test/test_admin_oauth2_middleware.py
index fe5a878a01c4..4f1c92bdffbb 100644
--- a/ee/api/test/test_admin_oauth2_middleware.py
+++ b/ee/api/test/test_admin_oauth2_middleware.py
@@ -22,6 +22,9 @@ from posthog.session.backend import SessionStore
from ee.middleware import AdminOAuth2Middleware, _get_email_from_id_token, admin_oauth2_callback
+# Any path under the prefix exercises the middleware branch; no route has to exist.
+ADMIN_API_PATH = "/admin/api/example/"
+
class JWTTestHelper:
"""Helper class for creating test JWT tokens."""
@@ -407,18 +410,16 @@ class TestMiddlewareVerification(BaseTest):
assert isinstance(response, HttpResponseRedirect)
self.assertIn("accounts.google.com", response.url)
- @parameterized.expand(
- [
- ("radar_bypass", "/admin/api/radar-bypass/"),
- ]
- )
@override_settings(
ADMIN_AUTH_GOOGLE_OAUTH2_KEY="test_client_id",
ADMIN_AUTH_GOOGLE_OAUTH2_SECRET="test_secret",
ADMIN_OAUTH2_COOKIE_SECURE=False,
)
- def test_api_admin_unverified_returns_403(self, _name, path):
- request = self.factory.get(path)
+ def test_api_admin_unverified_returns_403(self):
+ # No /admin/api/ route exists right now, but the middleware still branches on that
+ # prefix (ee/middleware.py) to answer 403 instead of redirecting to Google. The
+ # middleware is called directly here, so the branch is covered without a route.
+ request = self.factory.get(ADMIN_API_PATH)
request.user = self.user
request.session = SessionStore()
@@ -427,18 +428,13 @@ class TestMiddlewareVerification(BaseTest):
self.assertEqual(response.status_code, 403)
- @parameterized.expand(
- [
- ("radar_bypass", "/admin/api/radar-bypass/"),
- ]
- )
@override_settings(
ADMIN_AUTH_GOOGLE_OAUTH2_KEY="test_client_id",
ADMIN_AUTH_GOOGLE_OAUTH2_SECRET="test_secret",
ADMIN_OAUTH2_COOKIE_SECURE=False,
)
- def test_api_admin_verified_passes(self, _name, path):
- request = self.factory.get(path)
+ def test_api_admin_verified_passes(self):
+ request = self.factory.get(ADMIN_API_PATH)
request.user = self.user
request.session = SessionStore()
diff --git a/ee/urls.py b/ee/urls.py
index 11fa212b85ca..ce79ed1b59eb 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -102,7 +102,6 @@ if settings.ADMIN_PORTAL_ENABLED:
notebook_markdown_migration_stats_view,
notebook_markdown_migration_view,
)
- from posthog.admin.admins.radar_bypass_admin import RadarBypassViewSet, radar_bypass_view
from posthog.admin.admins.resave_cohorts_admin import resave_cohorts_view
from posthog.admin.admins.tophog_admin import tophog_dashboard_view, tophog_restrictions_view
@@ -115,21 +114,6 @@ if settings.ADMIN_PORTAL_ENABLED:
path("admin/redisvalues", redis_values_view, name="redis_values"),
path("admin/redis/edit-ttl", redis_edit_ttl_view, name="redis_edit_ttl"),
path("admin/apikeysearch", api_key_search_view, name="api_key_search"),
- path(
- "admin/radar-bypass/",
- admin.site.admin_view(radar_bypass_view),
- name="radar-bypass",
- ),
- path(
- "admin/api/radar-bypass/",
- RadarBypassViewSet.as_view({"get": "list", "post": "create"}),
- name="radar-bypass-api-list",
- ),
- path(
- "admin/api/radar-bypass/<str:email>/",
- RadarBypassViewSet.as_view({"delete": "destroy"}),
- name="radar-bypass-api-detail",
- ),
path(
"admin/resave-cohorts/",
admin.site.admin_view(resave_cohorts_view),
diff --git a/posthog/admin/admins/radar_bypass_admin.py b/posthog/admin/admins/radar_bypass_admin.py
deleted file mode 100644
index f4c3fa19df79..000000000000
--- a/posthog/admin/admins/radar_bypass_admin.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from django.contrib import admin
-from django.shortcuts import render
-
-from rest_framework import serializers, status, viewsets
-from rest_framework.permissions import IsAdminUser
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.redis import get_client
-from posthog.workos_radar import WORKOS_RADAR_BYPASS_REDIS_KEY, add_radar_bypass_email, remove_radar_bypass_email
-
-
-class RadarBypassEmailSerializer(serializers.Serializer):
- email = serializers.EmailField(help_text="Email address to bypass suspicious signup checks")
-
-
-class RadarBypassViewSet(viewsets.ViewSet):
- permission_classes = [IsAdminUser]
-
- def list(self, request: Request) -> Response:
- bypass_emails = sorted(
- member.decode() if isinstance(member, bytes) else member
- for member in get_client().smembers(WORKOS_RADAR_BYPASS_REDIS_KEY)
- )
- return Response(bypass_emails)
-
- def create(self, request: Request) -> Response:
- serializer = RadarBypassEmailSerializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- email = serializer.validated_data["email"]
- add_radar_bypass_email(email)
- return Response({"email": email}, status=status.HTTP_201_CREATED)
-
- def destroy(self, request: Request, email: str) -> Response:
- remove_radar_bypass_email(email)
- return Response(status=status.HTTP_204_NO_CONTENT)
-
-
-def radar_bypass_view(request):
- """Admin template view — thin wrapper that renders the HTML admin page."""
- bypass_emails = sorted(
- member.decode() if isinstance(member, bytes) else member
- for member in get_client().smembers(WORKOS_RADAR_BYPASS_REDIS_KEY)
- )
-
- context = {
- "bypass_emails": bypass_emails,
- "title": "Suspicious signup checks bypass",
- "has_view_permission": True,
- "site_title": admin.site.site_title,
- "site_header": admin.site.site_header,
- "site_url": admin.site.site_url,
- "has_permission": True,
- }
- return render(request, "admin/radar_bypass.html", context)
diff --git a/posthog/templates/admin/radar_bypass.html b/posthog/templates/admin/radar_bypass.html
deleted file mode 100644
index b542d61f8bf9..000000000000
--- a/posthog/templates/admin/radar_bypass.html
+++ /dev/null
@@ -1,149 +0,0 @@
-{% extends "admin/base_site.html" %}
-{% load i18n admin_urls static %}
-{% block extrastyle %}
- {{ block.super }}
- <style nonce="{{ request.csp_nonce }}">
- .form-row { margin-bottom: 15px; margin-top: 15px; }
- .help { font-size: 11px; color: #666; }
- .submit-row { margin-top: 20px; }
- .email-list { margin-top: 20px; }
- .email-list table { width: 100%; border-collapse: collapse; }
- .email-list th, .email-list td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #ddd; }
- .email-list th { background: #f8f8f8; font-weight: bold; }
- .remove-btn { color: #ba2121; cursor: pointer; background: none; border: none; text-decoration: underline; }
- .remove-btn:hover { color: #a41515; }
- .empty-state { color: #666; font-style: italic; padding: 12px 0; }
- .msg-success { background: #dfd; padding: 8px 12px; margin-bottom: 10px; border-radius: 4px; }
- .msg-error { background: #fdd; padding: 8px 12px; margin-bottom: 10px; border-radius: 4px; }
- </style>
-{% endblock %}
-{% block content %}
- <div id="messages"></div>
- <div class="email-list">
- <fieldset class="module aligned">
- <h2>Bypassed emails (<span id="email-count">{{ bypass_emails|length }}</span>)</h2>
- <table id="email-table"
- {% if not bypass_emails %}style="display:none"{% endif %}>
- <thead>
- <tr>
- <th>Email</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody id="email-list-body">
- {% for email in bypass_emails %}
- <tr data-email="{{ email }}">
- <td>{{ email }}</td>
- <td>
- <button type="button" class="remove-btn">Remove</button>
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <p id="empty-state"
- class="empty-state"
- {% if bypass_emails %}style="display:none"{% endif %}>No emails are currently bypassed.</p>
- </fieldset>
- </div>
- <form id="add-form" style="margin-top: 30px;">
- {% csrf_token %}
- <fieldset class="module aligned">
- <h2>Add email</h2>
- <div class="form-row">
- <label for="id_email">Email:</label>
- <input type="email" name="email" id="id_email" required />
- <p class="help">Email address to bypass suspicious signup checks</p>
- </div>
- </fieldset>
- <div class="submit-row">
- <input type="submit" value="Add to bypass list" class="default" />
- </div>
- </form>
- <script nonce="{{ request.csp_nonce }}">
-const API_BASE = '/admin/api/radar-bypass/';
-
-function getCSRFToken() {
- return document.querySelector('[name=csrfmiddlewaretoken]').value;
-}
-
-function showMessage(text, isError) {
- const el = document.getElementById('messages');
- el.textContent = '';
- const div = document.createElement('div');
- div.className = 'msg-' + (isError ? 'error' : 'success');
- div.textContent = text;
- el.appendChild(div);
- setTimeout(() => { el.textContent = ''; }, 4000);
-}
-
-function updateCount() {
- const rows = document.querySelectorAll('#email-list-body tr');
- document.getElementById('email-count').textContent = rows.length;
- document.getElementById('email-table').style.display = rows.length ? '' : 'none';
- document.getElementById('empty-state').style.display = rows.length ? 'none' : '';
-}
-
-function removeEmail(email) {
- if (!confirm('Remove ' + email + ' from bypass list?')) return;
-
- fetch(API_BASE + encodeURIComponent(email) + '/', {
- method: 'DELETE',
- headers: {'X-CSRFToken': getCSRFToken()},
- }).then(r => {
- if (r.ok || r.status === 204) {
- const row = document.querySelector('[data-email="' + CSS.escape(email) + '"]');
- if (row) row.remove();
- updateCount();
- showMessage('Removed ' + email + ' from bypass list.', false);
- } else {
- showMessage('Failed to remove email.', true);
- }
- });
-}
-
-function addEmail(e) {
- e.preventDefault();
- const input = document.getElementById('id_email');
- const email = input.value.trim();
- if (!email) return;
-
- fetch(API_BASE, {
- method: 'POST',
- headers: {'Content-Type': 'application/json', 'X-CSRFToken': getCSRFToken()},
- body: JSON.stringify({email: email})
- }).then(r => {
- if (r.ok) {
- const tbody = document.getElementById('email-list-body');
- const tr = document.createElement('tr');
- tr.dataset.email = email;
- const td1 = document.createElement('td');
- td1.textContent = email;
- const td2 = document.createElement('td');
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.className = 'remove-btn';
- btn.textContent = 'Remove';
- td2.appendChild(btn);
- tr.appendChild(td1);
- tr.appendChild(td2);
- tbody.appendChild(tr);
- input.value = '';
- updateCount();
- showMessage('Added ' + email + ' to bypass list.', false);
- } else {
- r.json().then(d => showMessage(d.email ? d.email[0] : 'Failed to add email.', true));
- }
- });
-}
-
-document.getElementById('add-form').addEventListener('submit', addEmail);
-
-document.getElementById('email-list-body').addEventListener('click', function(e) {
- const btn = e.target.closest('.remove-btn');
- if (!btn) return;
- const row = btn.closest('tr');
- if (row) removeEmail(row.dataset.email);
-});
- </script>
-{% endblock %}
diff --git a/posthog/templates/custom_tools/app.html b/posthog/templates/custom_tools/app.html
index f73416eab6e1..f8be62667faf 100644
--- a/posthog/templates/custom_tools/app.html
+++ b/posthog/templates/custom_tools/app.html
@@ -19,12 +19,6 @@
</td>
<td>Regenerate compiled bytecode and cohort_type for cohorts, with batch processing</td>
</tr>
- <tr class="model-radarbypass">
- <td scope="row">
- <a href="{% url 'radar-bypass' %}">Suspicious signup checks bypass</a>
- </td>
- <td>Manage email addresses that bypass suspicious signup checks (WorkOS Radar)</td>
- </tr>
<tr class="model-distinctidusage">
<td scope="row">
<a href="{% url 'distinct-id-usage' %}">Distinct ID usage</a>
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index 11614dc464cf..c03a8a4539b0 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -38,7 +38,6 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"ee.clickhouse.views.groups.GroupsViewSet",
"ee.clickhouse.views.person.EnterprisePersonViewSet",
"ee.clickhouse.views.person.LegacyEnterprisePersonViewSet",
- "posthog.admin.admins.radar_bypass_admin.RadarBypassViewSet",
"posthog.api.advanced_activity_logs.viewset.ActivityLogViewSet",
"posthog.api.advanced_activity_logs.viewset.AdvancedActivityLogsViewSet",
"posthog.api.advanced_activity_logs.viewset.OrganizationAdvancedActivityLogsViewSet",
diff --git a/posthog/test/test_workos_radar.py b/posthog/test/test_workos_radar.py
index 086ab0ee2dfe..8b754519c957 100644
--- a/posthog/test/test_workos_radar.py
+++ b/posthog/test/test_workos_radar.py
@@ -12,7 +12,6 @@ from parameterized import parameterized
from posthog.workos_radar import (
WORKOS_RADAR_API_URL,
- WORKOS_RADAR_BYPASS_REDIS_KEY,
ChallengeRequired,
RadarAction,
RadarAuthMethod,
@@ -22,10 +21,7 @@ from posthog.workos_radar import (
_get_raw_user_agent,
_hash_email,
_log_radar_event,
- add_radar_bypass_email,
evaluate_auth_attempt,
- is_radar_bypass_email,
- remove_radar_bypass_email,
)
@@ -367,9 +363,9 @@ class TestEvaluateAuthAttempt(TestCase):
@patch("posthog.workos_radar._log_radar_event")
@patch("posthog.workos_radar._call_radar_api")
- @patch("posthog.workos_radar.is_radar_bypass_email", return_value=True)
+ @patch("posthog.workos_radar.is_signup_risk_exempt", return_value=True)
@override_settings(WORKOS_RADAR_ENABLED=True, WORKOS_RADAR_API_KEY="test_key")
- def test_block_verdict_bypassed_for_whitelisted_email(self, mock_is_bypass, mock_call_api, mock_log_event):
+ def test_block_verdict_bypassed_for_exempt_email(self, mock_is_bypass, mock_call_api, mock_log_event):
mock_call_api.return_value = RadarVerdict.BLOCK
factory = RequestFactory()
request = factory.get("/", REMOTE_ADDR="1.2.3.4", HTTP_USER_AGENT="TestBrowser")
@@ -386,105 +382,7 @@ class TestEvaluateAuthAttempt(TestCase):
log_kwargs = mock_log_event.call_args[1]
assert log_kwargs["was_blocked"] is False
assert log_kwargs["was_bypassed"] is True
- assert log_kwargs["bypass_source"] == "legacy"
-
-
-class TestRadarBypassEmailRedis(TestCase):
- def setUp(self):
- from posthog.redis import get_client
-
- self.redis_client = get_client()
- self.redis_client.delete(WORKOS_RADAR_BYPASS_REDIS_KEY)
-
- def tearDown(self):
- self.redis_client.delete(WORKOS_RADAR_BYPASS_REDIS_KEY)
-
- def test_add_and_check_bypass_email(self):
- assert is_radar_bypass_email("[email protected]") is False
- add_radar_bypass_email("[email protected]")
- assert is_radar_bypass_email("[email protected]") is True
-
- def test_bypass_email_is_case_insensitive(self):
- add_radar_bypass_email("[email protected]")
- assert is_radar_bypass_email("[email protected]") is True
- assert is_radar_bypass_email("[email protected]") is True
-
- def test_remove_bypass_email(self):
- add_radar_bypass_email("[email protected]")
- assert is_radar_bypass_email("[email protected]") is True
- remove_radar_bypass_email("[email protected]")
- assert is_radar_bypass_email("[email protected]") is False
-
- def test_remove_nonexistent_email_is_noop(self):
- remove_radar_bypass_email("[email protected]")
- assert is_radar_bypass_email("[email protected]") is False
-
-
-class TestRadarBypassViewSet(TestCase):
- def setUp(self):
- from django.contrib.auth import get_user_model
-
- from posthog.redis import get_client
-
- User = get_user_model()
- self.staff_user = User.objects.create_user(
- email="[email protected]", password="testpass123!", is_staff=True, first_name="Admin"
- )
- self.non_staff_user = User.objects.create_user(
- email="[email protected]", password="testpass123!", is_staff=False, first_name="User"
- )
- self.redis_client = get_client()
- self.redis_client.delete(WORKOS_RADAR_BYPASS_REDIS_KEY)
-
- def tearDown(self):
- self.redis_client.delete(WORKOS_RADAR_BYPASS_REDIS_KEY)
-
- def test_non_staff_user_gets_403(self):
- self.client.force_login(self.non_staff_user)
- response = self.client.get("/admin/api/radar-bypass/")
- assert response.status_code == 403
-
- def test_list_bypass_emails(self):
- add_radar_bypass_email("[email protected]")
- add_radar_bypass_email("[email protected]")
- self.client.force_login(self.staff_user)
- response = self.client.get("/admin/api/radar-bypass/")
- assert response.status_code == 200
- assert sorted(response.json()) == ["[email protected]", "[email protected]"]
-
- def test_add_bypass_email(self):
- self.client.force_login(self.staff_user)
- response = self.client.post(
- "/admin/api/radar-bypass/",
- {"email": "[email protected]"},
- content_type="application/json",
- )
- assert response.status_code == 201
- assert response.json() == {"email": "[email protected]"}
- assert is_radar_bypass_email("[email protected]") is True
-
- def test_add_invalid_email_returns_400(self):
- self.client.force_login(self.staff_user)
- response = self.client.post(
- "/admin/api/radar-bypass/",
- {"email": "not-an-email"},
- content_type="application/json",
- )
- assert response.status_code == 400
- assert is_radar_bypass_email("not-an-email") is False
-
- def test_remove_bypass_email(self):
- add_radar_bypass_email("[email protected]")
- self.client.force_login(self.staff_user)
- response = self.client.delete("/admin/api/radar-bypass/[email protected]/")
- assert response.status_code == 204
- assert is_radar_bypass_email("[email protected]") is False
-
- def test_list_empty(self):
- self.client.force_login(self.staff_user)
- response = self.client.get("/admin/api/radar-bypass/")
- assert response.status_code == 200
- assert response.json() == []
+ assert log_kwargs["bypass_source"] == "rule"
class TestChallengeFlow(TestCase):
@@ -647,11 +545,11 @@ class TestChallengeFlow(TestCase):
auth_method=RadarAuthMethod.PASSWORD,
)
- @patch("posthog.workos_radar.is_radar_bypass_email", return_value=True)
+ @patch("posthog.workos_radar.is_signup_risk_exempt", return_value=True)
@patch("posthog.workos_radar._log_radar_event")
@patch("posthog.workos_radar._call_radar_api")
@override_settings(WORKOS_RADAR_ENABLED=True, WORKOS_RADAR_API_KEY="test_key")
- def test_challenge_verdict_bypassed_for_whitelisted_email(self, mock_call_api, mock_log_event, mock_is_bypass):
+ def test_challenge_verdict_bypassed_for_exempt_email(self, mock_call_api, mock_log_event, mock_is_bypass):
mock_call_api.return_value = RadarVerdict.CHALLENGE
factory = RequestFactory()
request = factory.get("/", REMOTE_ADDR="1.2.3.4", HTTP_USER_AGENT="TestBrowser")
@@ -666,5 +564,5 @@ class TestChallengeFlow(TestCase):
assert result == RadarVerdict.CHALLENGE
log_kwargs = mock_log_event.call_args[1]
assert log_kwargs["was_bypassed"] is True
- assert log_kwargs["bypass_source"] == "legacy"
+ assert log_kwargs["bypass_source"] == "rule"
assert log_kwargs["was_challenged"] is False
diff --git a/posthog/workos_radar.py b/posthog/workos_radar.py
index 245216d45355..ae97f322016c 100644
--- a/posthog/workos_radar.py
+++ b/posthog/workos_radar.py
@@ -4,9 +4,8 @@ WorkOS Radar integration for bot/fraud detection during authentication flows.
This module provides a client for the WorkOS Radar Attempts API to evaluate
signup attempts for potential fraud or bot activity. When Radar returns a
BLOCK verdict, the attempt is rejected with a SuspiciousAttemptBlocked
-exception unless the email is on the Redis bypass list managed via the
-admin tool, or a security access rule exempts it from the signup risk
-check.
+exception unless a security access rule exempts that address from the
+signup risk check.
"""
import time
@@ -22,7 +21,6 @@ import structlog
import posthoganalytics
from rest_framework.exceptions import APIException
-from posthog.redis import get_client
from posthog.turnstile import create_challenge_nonce, validate_and_consume_nonce, verify_turnstile_token
from posthog.utils import get_ip_address, get_short_user_agent
@@ -32,7 +30,6 @@ logger = structlog.get_logger(__name__)
WORKOS_RADAR_API_URL = "https://api.workos.com/radar/attempts"
WORKOS_RADAR_TIMEOUT = 5.0
-WORKOS_RADAR_BYPASS_REDIS_KEY = "workos_radar_bypass_emails"
class SuspiciousAttemptBlocked(APIException):
@@ -84,18 +81,6 @@ def _get_raw_user_agent(request: HttpRequest) -> str:
return request.headers.get("user-agent", "")
-def is_radar_bypass_email(email: str) -> bool:
- return bool(get_client().sismember(WORKOS_RADAR_BYPASS_REDIS_KEY, email.lower()))
-
-
-def add_radar_bypass_email(email: str) -> None:
- get_client().sadd(WORKOS_RADAR_BYPASS_REDIS_KEY, email.lower())
-
-
-def remove_radar_bypass_email(email: str) -> None:
- get_client().srem(WORKOS_RADAR_BYPASS_REDIS_KEY, email.lower())
-
-
def evaluate_auth_attempt(
request: HttpRequest,
email: str,
@@ -109,8 +94,8 @@ def evaluate_auth_attempt(
Evaluate an authentication attempt using the WorkOS Radar Attempts API.
Raises:
- SuspiciousAttemptBlocked: When verdict is BLOCK and the email is
- not in the Redis bypass list and not exempted by an access rule.
+ SuspiciousAttemptBlocked: When verdict is BLOCK and no access rule
+ exempts the address from the signup risk check.
ChallengeRequired: When verdict is CHALLENGE and no valid Turnstile
token was provided.
"""
@@ -145,8 +130,10 @@ def evaluate_auth_attempt(
user_agent=short_user_agent,
duration_ms=duration_ms,
was_blocked=outcome == "block",
- was_bypassed=outcome.startswith("bypass"),
- bypass_source=outcome.removeprefix("bypass_") if outcome.startswith("bypass") else None,
+ was_bypassed=outcome == "bypass",
+ # Only access rules bypass Radar now, but the property stays so queries written
+ # while the Redis list existed keep working and the event still says why.
+ bypass_source="rule" if outcome == "bypass" else None,
was_challenged=outcome == "challenge",
was_challenge_completed=outcome == "completed",
)
@@ -194,20 +181,6 @@ 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,
@@ -215,21 +188,14 @@ def _decide_outcome(
challenge_nonce: str,
ip_address: str,
) -> str:
- """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.
- """
+ """Return one of: 'allow', 'block', 'bypass', 'challenge', 'completed'."""
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):
- if _legacy_bypass(email):
- return "bypass_legacy"
- if is_signup_risk_exempt(email):
- return "bypass_rule"
+ if verdict in (RadarVerdict.BLOCK, RadarVerdict.CHALLENGE) and is_signup_risk_exempt(email):
+ return "bypass"
if verdict == RadarVerdict.BLOCK:
return "block"
diff --git a/products/security/backend/facade/hub.py b/products/security/backend/facade/hub.py
index d5a670934f68..7207ea90e05a 100644
--- a/products/security/backend/facade/hub.py
+++ b/products/security/backend/facade/hub.py
@@ -18,7 +18,6 @@ from ..logic.hub_auth import (
INTERNAL_PURPOSE as INTERNAL_PURPOSE,
claims_allow,
)
-from ..logic.radar_export import export_radar_bypasses
from ..metrics import HUB_API_AUTH_COUNTER
@@ -38,10 +37,6 @@ def posthog_account_exists(*, user_uuid: str | None = None, organization_id: str
return 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/radar_export.py b/products/security/backend/logic/radar_export.py
deleted file mode 100644
index c54869e7870e..000000000000
--- a/products/security/backend/logic/radar_export.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""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/logic/rules.py b/products/security/backend/logic/rules.py
index 044b2357b8f8..3f1bc76c5024 100644
--- a/products/security/backend/logic/rules.py
+++ b/products/security/backend/logic/rules.py
@@ -50,10 +50,19 @@ class SnapshotRule:
except ValueError:
return None
+ # The hub normalizes a target value when the rule is written, and a subject's address
+ # is normalized at decision time, so the two already meet in the middle. Folding the
+ # case again here costs nothing and closes a silent failure: a rule that reached the
+ # snapshot un-normalized would match nobody, and nothing would report it. The Redis
+ # list this replaced lowercased on read, so it could not be defeated that way.
+ target_value = values["targetValue"]
+ if values["targetType"] in ("email", "email_root", "email_domain"):
+ target_value = target_value.strip().lower()
+
return cls(
id=values["id"],
target_type=values["targetType"],
- target_value=values["targetValue"],
+ target_value=target_value,
effect=values["effect"],
scope=values["scope"],
expires_at=expires_at,
diff --git a/products/security/backend/presentation/hub_api.py b/products/security/backend/presentation/hub_api.py
index 15e507c0a18e..c750ead6d7ed 100644
--- a/products/security/backend/presentation/hub_api.py
+++ b/products/security/backend/presentation/hub_api.py
@@ -27,7 +27,6 @@ from ..facade.hub import (
count_accounts,
count_org_members,
posthog_account_exists,
- radar_bypasses,
record_call,
resolve,
token_allows,
@@ -40,7 +39,6 @@ from .serializers import (
OrgMemberCountResponseSerializer,
PosthogMembershipRequestSerializer,
PosthogMembershipResponseSerializer,
- RadarBypassExportResponseSerializer,
ResolveRequestSerializer,
ResolveResponseSerializer,
)
@@ -143,22 +141,6 @@ 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"
@@ -178,6 +160,5 @@ 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.py
index 6e7ffe006edf..693fea81f723 100644
--- a/products/security/backend/presentation/serializers.py
+++ b/products/security/backend/presentation/serializers.py
@@ -68,9 +68,3 @@ 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.py
index a0ab4e776e86..1714f4d2762a 100644
--- a/products/security/backend/tests/test_hub_api.py
+++ b/products/security/backend/tests/test_hub_api.py
@@ -12,7 +12,6 @@ from parameterized import parameterized
from rest_framework.test import APIClient
from posthog.models import User
-from posthog.workos_radar import add_radar_bypass_email, remove_radar_bypass_email
SECRET = "in-us"
SETTINGS = {"SECURITY_HUB_REGION": "us", "SECURITY_HUB_INBOUND_JWT_SECRETS": [SECRET]}
@@ -99,16 +98,6 @@ 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 == 202
diff --git a/products/security/backend/tests/test_radar_call_site.py b/products/security/backend/tests/test_radar_call_site.py
index b43a528f542c..b2fe20c18915 100644
--- a/products/security/backend/tests/test_radar_call_site.py
+++ b/products/security/backend/tests/test_radar_call_site.py
@@ -4,21 +4,16 @@ 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 posthog.workos_radar import RadarVerdict, _decide_outcome
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"
+ assert _decide_outcome(verdict, "[email protected]", "", "", "93.184.216.1") == "bypass"
def test_other_addresses_keep_the_verdict(self) -> None:
seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))
@@ -29,22 +24,97 @@ class TestRadarCallSite(SimpleTestCase):
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:
+ def test_an_address_with_no_rule_is_refused(self) -> None:
+ # The Redis list used to answer here. With it gone, an address nobody wrote a rule
+ # for keeps the verdict instead of being waved through.
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"
+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"
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:
+ def test_an_unreadable_snapshot_keeps_the_verdict(self) -> None:
+ # The rule check is now the only bypass, so its failure mode matters more than it
+ # did: it swallows errors and returns False, refusing the signup rather than
+ # waving it through.
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"
+ with patch("products.security.backend.facade.api.current_snapshot", side_effect=RuntimeError("redis down")):
+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"
+
+
+class TestRedisBypassEquivalence(SimpleTestCase):
+ """What the deleted Redis list did, restated against access rules.
+
+ The old check was one line: `sismember(key, email.lower())`, consulted only for a
+ BLOCK or CHALLENGE verdict. Every case below pins a property of that check, so a
+ later change to rule matching cannot quietly narrow what used to be exempt.
+ """
+
+ @parameterized.expand(
+ [
+ ("stored lower, sent upper", "[email protected]", "[email protected]"),
+ ("stored lower, sent mixed", "[email protected]", "[email protected]"),
+ ("stored mixed, sent lower", "[email protected]", "[email protected]"),
+ ]
+ )
+ def test_case_is_ignored_on_both_sides(self, _name: str, stored: str, sent: str) -> None:
+ # `add_radar_bypass_email` lowercased on write and `is_radar_bypass_email` on read,
+ # so case never mattered. Rule normalization has to fold both the same way.
+ seed_rules(exempt_rule(targetValue=stored, scope="signup_risk"))
+ assert _decide_outcome(RadarVerdict.BLOCK, sent, "", "", "93.184.216.1") == "bypass"
+
+ def test_surrounding_whitespace_still_matches(self) -> None:
+ # The old check did not trim, so " [email protected] " missed. Rules trim, which is a superset:
+ # anything the list exempted is still exempt.
+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))
+ assert _decide_outcome(RadarVerdict.BLOCK, " [email protected] ", "", "", "93.184.216.1") == "bypass"
+
+ @parameterized.expand(
+ [
+ ("plus tag", "[email protected]"),
+ ("dots moved", "[email protected]"),
+ ("different domain", "[email protected]"),
+ ("subdomain of the address domain", "[email protected]"),
+ ]
+ )
+ def test_an_exact_address_rule_does_not_widen(self, _name: str, sent: str) -> None:
+ # The old list matched the whole string. An address rule has to behave the same, or
+ # the cut-over would exempt people the Redis list never did.
+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))
+ assert _decide_outcome(RadarVerdict.BLOCK, sent, "", "", "93.184.216.1") == "block"
+
+ @parameterized.expand([(RadarVerdict.ALLOW,), (RadarVerdict.ERROR,), (RadarVerdict.DISABLED,)])
+ def test_verdicts_that_never_consulted_the_list(self, verdict: RadarVerdict) -> None:
+ # The old guard ran only for BLOCK and CHALLENGE. Everything else fell through to
+ # "allow" without a lookup, and still must.
+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk"))
+ assert _decide_outcome(verdict, "[email protected]", "", "", "93.184.216.1") == "allow"
+
+ def test_an_expired_rule_does_not_exempt(self) -> None:
+ # A Redis entry never expired. A rule can, and that is the one way the new mechanism
+ # can be narrower than the old one, so it is pinned: expiry means the verdict stands.
+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk", expiresAt="2020-01-01T00:00:00Z"))
+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"
+
+ def test_a_far_future_expiry_still_exempts(self) -> None:
+ seed_rules(exempt_rule(targetValue="[email protected]", scope="signup_risk", expiresAt="2099-01-01T00:00:00Z"))
+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "bypass"
+
+ @patch("posthog.workos_radar.verify_turnstile_token", return_value=True)
+ @patch("posthog.workos_radar.validate_and_consume_nonce", return_value=True)
+ def test_the_challenge_resubmit_path_is_unchanged(self, _nonce: object, _token: object) -> None:
+ # A resubmit with a token and nonce returned before the bypass check and never read
+ # Redis. It must not read the rules either, or a challenge could resolve differently.
+ seed_rules()
+ assert (
+ _decide_outcome(RadarVerdict.CHALLENGE, "[email protected]", "tok", "nonce", "93.184.216.1") == "completed"
+ )
+
+ def test_a_domain_rule_covers_the_addresses_a_list_would_have_held(self) -> None:
+ # Strictly wider than the old list, and the reason the hub can replace it: one rule
+ # covers a domain and its subdomains instead of one entry per address.
+ seed_rules(exempt_rule(targetType="email_domain", targetValue="partner.example", scope="signup_risk"))
+ assert _decide_outcome(RadarVerdict.BLOCK, sent, "", "", "93.184.216.1") == "bypass"
+ assert _decide_outcome(RadarVerdict.BLOCK, "[email protected]", "", "", "93.184.216.1") == "block"