: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
chore(security): remove the legacy email-MFA bypass machinery (#106912)
Yasen4ef52ca84c2f
diff --git a/ee/api/test/test_admin_oauth2_middleware.py b/ee/api/test/test_admin_oauth2_middleware.pyindex 3287bcd40dc9..fe5a878a01c4 100644--- a/ee/api/test/test_admin_oauth2_middleware.py+++ b/ee/api/test/test_admin_oauth2_middleware.py@@ -410,7 +410,6 @@ class TestMiddlewareVerification(BaseTest):@parameterized.expand([("radar_bypass", "/admin/api/radar-bypass/"),- ("code_based_verification_bypass", "/admin/api/code-based-verification-bypass/"),])@override_settings(@@ -431,7 +430,6 @@ class TestMiddlewareVerification(BaseTest):@parameterized.expand([("radar_bypass", "/admin/api/radar-bypass/"),- ("code_based_verification_bypass", "/admin/api/code-based-verification-bypass/"),])@override_settings(diff --git a/ee/urls.py b/ee/urls.pyindex 80c7de2e5ab3..11fa212b85ca 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -91,11 +91,6 @@ if settings.ADMIN_PORTAL_ENABLED:except NotRegistered:pass- from posthog.admin.admins.code_based_verification_bypass_admin import (- CodeBasedVerificationBypassViewSet,- CodeBasedVerificationGlobalDisableViewSet,- code_based_verification_bypass_view,- )from posthog.admin.admins.distinct_id_usage_admin import distinct_id_usage_viewfrom posthog.admin.admins.health_check_admin import (health_check_list_view,@@ -135,26 +130,6 @@ if settings.ADMIN_PORTAL_ENABLED:RadarBypassViewSet.as_view({"delete": "destroy"}),name="radar-bypass-api-detail",),- path(- "admin/code-based-verification-bypass/",- admin.site.admin_view(code_based_verification_bypass_view),- name="code-based-verification-bypass",- ),- path(- "admin/api/code-based-verification-bypass/",- CodeBasedVerificationBypassViewSet.as_view({"get": "list", "post": "create"}),- name="code-based-verification-bypass-api-list",- ),- path(- "admin/api/code-based-verification-bypass/<str:email>/",- CodeBasedVerificationBypassViewSet.as_view({"delete": "destroy"}),- name="code-based-verification-bypass-api-detail",- ),- path(- "admin/api/code-based-verification-global-disable/",- CodeBasedVerificationGlobalDisableViewSet.as_view({"get": "list", "post": "create", "delete": "destroy"}),- name="code-based-verification-global-disable-api",- ),path("admin/resave-cohorts/",admin.site.admin_view(resave_cohorts_view),diff --git a/posthog/admin/admins/code_based_verification_bypass_admin.py b/posthog/admin/admins/code_based_verification_bypass_admin.pydeleted file mode 100644index 6ca1677b8e88..000000000000--- a/posthog/admin/admins/code_based_verification_bypass_admin.py+++ /dev/null@@ -1,104 +0,0 @@-from typing import cast--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.helpers.two_factor_session import (- CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY,- MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,- add_code_based_verification_bypass,- clear_code_based_verification_global_disable,- get_code_based_verification_global_disable,- remove_code_based_verification_bypass,- set_code_based_verification_global_disable,-)-from posthog.models.user import User-from posthog.redis import get_client---class CodeBasedVerificationBypassEmailSerializer(serializers.Serializer):- email = serializers.EmailField(help_text="Email address to bypass code-based verification")---class CodeBasedVerificationGlobalDisableSerializer(serializers.Serializer):- reason = serializers.CharField(- allow_blank=False, help_text="Why code-based verification is being disabled globally"- )- ttl_seconds = serializers.IntegerField(- min_value=1,- max_value=MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,- help_text="How long the disable lasts, in seconds (max 7 days)",- )---class CodeBasedVerificationGlobalDisableViewSet(viewsets.ViewSet):- """Completely disable code-based verification for all users, with a required reason and TTL."""-- permission_classes = [IsAdminUser]-- def list(self, request: Request) -> Response:- state = get_code_based_verification_global_disable()- return Response({"disabled": state is not None, "state": state})-- def create(self, request: Request) -> Response:- serializer = CodeBasedVerificationGlobalDisableSerializer(data=request.data)- serializer.is_valid(raise_exception=True)- set_code_based_verification_global_disable(- reason=serializer.validated_data["reason"],- ttl_seconds=serializer.validated_data["ttl_seconds"],- disabled_by=cast(User, request.user).email,- )- return Response(- {"disabled": True, "state": get_code_based_verification_global_disable()}, status=status.HTTP_201_CREATED- )-- def destroy(self, request: Request) -> Response:- clear_code_based_verification_global_disable()- return Response(status=status.HTTP_204_NO_CONTENT)---class CodeBasedVerificationBypassViewSet(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(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY)- )- return Response(bypass_emails)-- def create(self, request: Request) -> Response:- serializer = CodeBasedVerificationBypassEmailSerializer(data=request.data)- serializer.is_valid(raise_exception=True)- email = serializer.validated_data["email"]- add_code_based_verification_bypass(email)- return Response({"email": email}, status=status.HTTP_201_CREATED)-- def destroy(self, request: Request, email: str) -> Response:- remove_code_based_verification_bypass(email)- return Response(status=status.HTTP_204_NO_CONTENT)---def code_based_verification_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(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY)- )-- context = {- "bypass_emails": bypass_emails,- "global_disable": get_code_based_verification_global_disable(),- "title": "Code-based verification 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/code_based_verification_bypass.html", context)diff --git a/posthog/admin/test_code_based_verification_global_disable_admin.py b/posthog/admin/test_code_based_verification_global_disable_admin.pydeleted file mode 100644index 1226330e55f5..000000000000--- a/posthog/admin/test_code_based_verification_global_disable_admin.py+++ /dev/null@@ -1,81 +0,0 @@-from posthog.test.base import APIBaseTest--from rest_framework import status-from rest_framework.test import APIRequestFactory, force_authenticate--from posthog.admin.admins.code_based_verification_bypass_admin import CodeBasedVerificationGlobalDisableViewSet-from posthog.helpers.two_factor_session import (- MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,- clear_code_based_verification_global_disable,- is_code_based_verification_globally_disabled,-)---class TestCodeBasedVerificationGlobalDisableAdmin(APIBaseTest):- def setUp(self):- super().setUp()- clear_code_based_verification_global_disable()- self.factory = APIRequestFactory()-- def tearDown(self):- clear_code_based_verification_global_disable()- super().tearDown()-- def _make_staff(self):- self.user.is_staff = True- self.user.save()-- def test_non_staff_is_forbidden(self):- request = self.factory.get("/admin/api/code-based-verification-global-disable/")- force_authenticate(request, user=self.user)- response = CodeBasedVerificationGlobalDisableViewSet.as_view({"get": "list"})(request)- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)-- def test_staff_can_disable_list_and_clear(self):- self._make_staff()-- request = self.factory.post(- "/admin/api/code-based-verification-global-disable/",- {"reason": "email outage", "ttl_seconds": 3600},- format="json",- )- force_authenticate(request, user=self.user)- response = CodeBasedVerificationGlobalDisableViewSet.as_view({"post": "create"})(request)- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertTrue(is_code_based_verification_globally_disabled())- self.assertEqual(response.data["state"]["disabled_by"], self.user.email)- self.assertEqual(response.data["state"]["reason"], "email outage")-- request = self.factory.get("/admin/api/code-based-verification-global-disable/")- force_authenticate(request, user=self.user)- response = CodeBasedVerificationGlobalDisableViewSet.as_view({"get": "list"})(request)- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertTrue(response.data["disabled"])-- request = self.factory.delete("/admin/api/code-based-verification-global-disable/")- force_authenticate(request, user=self.user)- response = CodeBasedVerificationGlobalDisableViewSet.as_view({"delete": "destroy"})(request)- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)- self.assertFalse(is_code_based_verification_globally_disabled())-- def test_reason_is_required(self):- self._make_staff()- request = self.factory.post(- "/admin/api/code-based-verification-global-disable/", {"reason": "", "ttl_seconds": 3600}, format="json"- )- force_authenticate(request, user=self.user)- response = CodeBasedVerificationGlobalDisableViewSet.as_view({"post": "create"})(request)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(is_code_based_verification_globally_disabled())-- def test_ttl_cap_is_enforced(self):- self._make_staff()- request = self.factory.post(- "/admin/api/code-based-verification-global-disable/",- {"reason": "too long", "ttl_seconds": MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS + 1},- format="json",- )- force_authenticate(request, user=self.user)- response = CodeBasedVerificationGlobalDisableViewSet.as_view({"post": "create"})(request)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(is_code_based_verification_globally_disabled())diff --git a/posthog/helpers/tests/test_two_factor_session.py b/posthog/helpers/tests/test_two_factor_session.pyindex ee39e857eb85..551fbe3696d3 100644--- a/posthog/helpers/tests/test_two_factor_session.py+++ b/posthog/helpers/tests/test_two_factor_session.py@@ -5,18 +5,8 @@ from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase-from parameterized import parameterized-from posthog.helpers.email_utils import ESPSuppressionReason, ESPSuppressionResult-from posthog.helpers.two_factor_session import (- MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,- CodeBasedVerificationCheckResult,- CodeBasedVerifier,- clear_code_based_verification_global_disable,- get_code_based_verification_global_disable,- is_code_based_verification_globally_disabled,- set_code_based_verification_global_disable,-)+from posthog.helpers.two_factor_session import CodeBasedVerificationCheckResult, CodeBasedVerifier@pytest.mark.disable_mock_code_based_verifier@@ -209,80 +199,3 @@ class TestCodeBasedVerifierSuppressionIntegration(SimpleTestCase):call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "code_based_verification_bypassed_due_to_suppression")self.assertEqual(call_kwargs["properties"]["reason"], ESPSuppressionReason.NO_EMAIL_HTTP_SERVICE)---class TestCodeBasedVerificationGlobalDisable(SimpleTestCase):- def setUp(self):- clear_code_based_verification_global_disable()-- def tearDown(self):- clear_code_based_verification_global_disable()-- def test_not_disabled_by_default(self):- self.assertFalse(is_code_based_verification_globally_disabled())- self.assertIsNone(get_code_based_verification_global_disable())-- def test_set_get_clear_round_trip(self):- set_code_based_verification_global_disable(- reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]"- )-- self.assertTrue(is_code_based_verification_globally_disabled())- state = get_code_based_verification_global_disable()- assert state is not None- self.assertEqual(state["reason"], "email pipeline down")- self.assertEqual(state["disabled_by"], "[email protected]")- self.assertIn("disabled_at", state)- self.assertTrue(0 < state["expires_in_seconds"] <= 3600)-- clear_code_based_verification_global_disable()- self.assertFalse(is_code_based_verification_globally_disabled())- self.assertIsNone(get_code_based_verification_global_disable())-- def test_reason_is_stripped_and_required(self):- with self.assertRaises(ValueError):- set_code_based_verification_global_disable(- reason=" ", ttl_seconds=3600, disabled_by="[email protected]"- )- self.assertFalse(is_code_based_verification_globally_disabled())-- @parameterized.expand(- [- ("zero", 0),- ("negative", -1),- ("over_max", MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS + 1),- ]- )- def test_invalid_ttl_rejected(self, _name, ttl_seconds):- with self.assertRaises(ValueError):- set_code_based_verification_global_disable(- reason="reason", ttl_seconds=ttl_seconds, disabled_by="[email protected]"- )- self.assertFalse(is_code_based_verification_globally_disabled())-- def test_max_ttl_accepted(self):- set_code_based_verification_global_disable(- reason="reason",- ttl_seconds=MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,- disabled_by="[email protected]",- )- self.assertTrue(is_code_based_verification_globally_disabled())-- @pytest.mark.disable_mock_code_based_verifier- def test_global_disable_skips_code_based_verification(self):- user = MagicMock()- user.pk = 1- user.email = "[email protected]"-- set_code_based_verification_global_disable(- reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]"- )- result = CodeBasedVerifier().should_send_code_based_verification(user)- self.assertEqual(result, CodeBasedVerificationCheckResult(should_send=False))-- @patch("posthog.helpers.two_factor_session.get_client")- def test_fails_closed_when_redis_unavailable(self, mock_get_client):- mock_get_client.side_effect = Exception("redis unreachable")- # Reads must not raise, and must default to "not disabled" so email MFA stays enforced.- self.assertFalse(is_code_based_verification_globally_disabled())- self.assertIsNone(get_code_based_verification_global_disable())diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex 2e5b950fd1bd..daa00c2b842c 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -1,5 +1,4 @@import re-import jsonimport timeimport datetimeimport unicodedata@@ -30,77 +29,6 @@ from posthog.settings.web import AUTHENTICATION_BACKENDSfrom products.security.backend.facade.api import is_email_code_exempt-CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY = "code_based_verification_bypass_emails"---def is_code_based_verification_bypass(email: str) -> bool:- return bool(get_client().sismember(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY, email.lower()))---def add_code_based_verification_bypass(email: str) -> None:- get_client().sadd(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY, email.lower())---def remove_code_based_verification_bypass(email: str) -> None:- get_client().srem(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY, email.lower())---# Global kill-switch: when this Redis key is present, code-based verification is skipped for every-# user (e.g. while transactional email delivery is down and the login code can't be delivered).-# The key carries the reason/actor/timestamp and a mandatory TTL so it auto-re-enables.-# Only the email factor is affected — TOTP and passkey 2FA are gated earlier in the login flow.-CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY = "code_based_verification_global_disable"-MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days---def is_code_based_verification_globally_disabled() -> bool:- # Fail closed: if Redis is unreachable, keep code-based verification enforced (the secure default) rather than- # silently dropping the second factor — and never let a Redis hiccup break the login flow.- try:- return bool(get_client().exists(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY))- except Exception:- mfa_logger.exception(- "Failed to read code-based verification global disable flag; keeping code-based verification enforced"- )- return False---def get_code_based_verification_global_disable() -> Optional[dict]:- try:- client = get_client()- raw = client.get(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY)- if not raw:- return None- data = json.loads(raw)- ttl = client.ttl(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY)- data["expires_in_seconds"] = ttl if isinstance(ttl, int) and ttl > 0 else None- return data- except Exception:- mfa_logger.exception("Failed to read code-based verification global disable state")- return None---def set_code_based_verification_global_disable(reason: str, ttl_seconds: int, disabled_by: str) -> None:- reason = (reason or "").strip()- if not reason:- raise ValueError("A reason is required to disable code-based verification.")- if not 0 < ttl_seconds <= MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS:- raise ValueError(- f"TTL must be between 1 second and {MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS} seconds (7 days)."- )- payload = json.dumps(- {- "reason": reason,- "disabled_by": disabled_by,- "disabled_at": datetime.datetime.now(datetime.UTC).isoformat(),- }- )- get_client().set(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY, payload, ex=ttl_seconds)---def clear_code_based_verification_global_disable() -> None:- get_client().delete(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY)-def has_passkeys(user: User) -> bool:"""@@ -401,9 +329,6 @@ class CodeBasedVerifier:)def should_send_code_based_verification(self, user: User) -> CodeBasedVerificationCheckResult:- if is_code_based_verification_globally_disabled():- return CodeBasedVerificationCheckResult(should_send=False)-if is_dev_mode() and not settings.TEST:return CodeBasedVerificationCheckResult(should_send=False)@@ -423,10 +348,7 @@ class CodeBasedVerifier:suppression_cached=False,)- if is_code_based_verification_bypass(user.email):- mfa_logger.info("Code-based verification bypassed via admin bypass list", user_id=user.pk)- return CodeBasedVerificationCheckResult(should_send=False)-+ # An exempting rule drops only the emailed code. TOTP and passkey 2FA are gated earlier in the login flow.if is_email_code_exempt(user.email):mfa_logger.info("Code-based verification bypassed via access rule", user_id=user.pk)return CodeBasedVerificationCheckResult(should_send=False)diff --git a/posthog/templates/admin/code_based_verification_bypass.html b/posthog/templates/admin/code_based_verification_bypass.htmldeleted file mode 100644index 5f0b3c941260..000000000000--- a/posthog/templates/admin/code_based_verification_bypass.html+++ /dev/null@@ -1,268 +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 id="global-disable" style="margin-bottom: 30px;">- <fieldset class="module aligned">- <h2>Global email MFA disable</h2>- {% if global_disable %}- <div class="msg-error">- <strong>Email MFA is currently DISABLED for all users.</strong>- <br />- Reason: {{ global_disable.reason }}- <br />- Disabled by: {{ global_disable.disabled_by }}- <br />- Disabled at: {{ global_disable.disabled_at }}- <br />- {% if global_disable.expires_in_seconds %}Auto re-enables in ~{{ global_disable.expires_in_seconds }} seconds.{% endif %}- </div>- <div class="submit-row">- <button type="button" id="reenable-btn" class="default">Re-enable email MFA now</button>- </div>- {% else %}- <p class="empty-state">Email MFA is currently enabled for all users.</p>- <form id="disable-form">- {% csrf_token %}- <div class="form-row">- <label for="id_reason">Reason:</label>- <input type="text" name="reason" id="id_reason" required />- <p class="help">Why email MFA is being disabled. Required and stored for audit.</p>- </div>- <div class="form-row">- <label for="id_duration">Duration:</label>- <input type="number"- id="id_duration"- min="1"- value="6"- style="width: 80px"- required />- <select id="id_duration_unit">- <option value="60">minutes</option>- <option value="3600" selected>hours</option>- <option value="86400">days</option>- </select>- <p class="help">Auto re-enables after this. Maximum 7 days.</p>- </div>- <div class="submit-row">- <input type="submit" value="Disable email MFA for all users" class="default" />- </div>- </form>- {% endif %}- </fieldset>- </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 email MFA verification</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/code-based-verification-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().toLowerCase();- if (!email) return;-- const existingRow = document.querySelector('[data-email="' + CSS.escape(email) + '"]');- if (existingRow) {- showMessage('Email is already in the bypass list.', true);- 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);-});--// --- Global email MFA disable ----const GLOBAL_API = '/admin/api/code-based-verification-global-disable/';-const MAX_TTL_SECONDS = 7 * 24 * 60 * 60;--const disableForm = document.getElementById('disable-form');-if (disableForm) {- disableForm.addEventListener('submit', function(e) {- e.preventDefault();- const reason = document.getElementById('id_reason').value.trim();- const amount = parseInt(document.getElementById('id_duration').value, 10);- const unit = parseInt(document.getElementById('id_duration_unit').value, 10);- if (!reason) { showMessage('A reason is required.', true); return; }- if (!amount || amount < 1) { showMessage('Enter a valid duration.', true); return; }- const ttlSeconds = amount * unit;- if (ttlSeconds > MAX_TTL_SECONDS) { showMessage('Duration cannot exceed 7 days.', true); return; }-- const submitBtn = disableForm.querySelector('input[type="submit"]');- submitBtn.disabled = true;- submitBtn.value = 'Disabling…';- fetch(GLOBAL_API, {- method: 'POST',- headers: {'Content-Type': 'application/json', 'X-CSRFToken': getCSRFToken()},- body: JSON.stringify({reason: reason, ttl_seconds: ttlSeconds})- }).then(r => {- if (r.ok) {- window.location.reload();- } else {- r.json().then(d => showMessage(d.reason ? d.reason[0] : (d.ttl_seconds ? d.ttl_seconds[0] : 'Failed to disable email MFA.'), true));- submitBtn.disabled = false;- submitBtn.value = 'Disable email MFA for all users';- }- }).catch(() => {- showMessage('Failed to disable email MFA.', true);- submitBtn.disabled = false;- submitBtn.value = 'Disable email MFA for all users';- });- });-}--const reenableBtn = document.getElementById('reenable-btn');-if (reenableBtn) {- reenableBtn.addEventListener('click', function() {- if (!confirm('Re-enable email MFA for all users now?')) return;- reenableBtn.disabled = true;- reenableBtn.textContent = 'Re-enabling…';- fetch(GLOBAL_API, {- method: 'DELETE',- headers: {'X-CSRFToken': getCSRFToken()},- }).then(r => {- if (r.ok || r.status === 204) {- window.location.reload();- } else {- showMessage('Failed to re-enable email MFA.', true);- reenableBtn.disabled = false;- reenableBtn.textContent = 'Re-enable email MFA now';- }- }).catch(() => {- showMessage('Failed to re-enable email MFA.', true);- reenableBtn.disabled = false;- reenableBtn.textContent = 'Re-enable email MFA now';- });- });-}- </script>-{% endblock %}diff --git a/posthog/templates/custom_tools/app.html b/posthog/templates/custom_tools/app.htmlindex 91c3495c1002..f73416eab6e1 100644--- a/posthog/templates/custom_tools/app.html+++ b/posthog/templates/custom_tools/app.html@@ -25,12 +25,6 @@</td><td>Manage email addresses that bypass suspicious signup checks (WorkOS Radar)</td></tr>- <tr class="model-codebasedverificationbypass">- <td scope="row">- <a href="{% url 'code-based-verification-bypass' %}">Email MFA bypass</a>- </td>- <td>Manage email addresses that bypass email MFA verification</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.pyindex 47d8ffd41683..b930041de944 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -37,8 +37,6 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"ee.clickhouse.views.groups.GroupsViewSet","ee.clickhouse.views.person.EnterprisePersonViewSet","ee.clickhouse.views.person.LegacyEnterprisePersonViewSet",- "posthog.admin.admins.code_based_verification_bypass_admin.CodeBasedVerificationBypassViewSet",- "posthog.admin.admins.code_based_verification_bypass_admin.CodeBasedVerificationGlobalDisableViewSet","posthog.admin.admins.radar_bypass_admin.RadarBypassViewSet","posthog.api.advanced_activity_logs.viewset.ActivityLogViewSet","posthog.api.advanced_activity_logs.viewset.AdvancedActivityLogsViewSet",diff --git a/products/security/README.md b/products/security/README.mdindex ef90ca24d485..67abd933c094 100644--- a/products/security/README.md+++ b/products/security/README.md@@ -12,13 +12,16 @@ This product pulls them, decides them in-process, and answers the hub's question- `facade.api.decide(subject, surface)` returns allow, block or exempt with the deciding rule.A posthog.com account is never blocked.- Phase 1 enforces only `email_code` exemptions. Signup, login, sessions and the AI gateway call `shadow_check`, which logs `security_access_would_block` and counts `posthog_security_access_would_block_total`, and blocks nobody.+- To drop the emailed login code for every account during an email outage, add an `everyone` rule with scope `email_code` at the hub.+ Give it an expiry. The Redis switch it replaces capped itself at 7 days; a rule without `expiresAt` stays in force until somebody revokes it.+ It applies on the next pull plus the memo window, so allow about 6 minutes.## Hub endpoints-`/api/security/{resolve,count-accounts,org-member-count,posthog-membership,sync-now,mfa-bypass-export}/`.+`/api/security/{resolve,count-accounts,org-member-count,posthog-membership,sync-now}/`.They are public because the hub runs outside the cluster.A scoped HS256 token (`posthog:security_hub:internal`) pinned to this region and one operation is the only gate.-All six routes share one limit of 100 requests per minute.+All five routes share one limit of 100 requests per minute.## Settingsdiff --git a/products/security/backend/facade/hub.py b/products/security/backend/facade/hub.pyindex 7b1adda09875..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.mfa_export import MfaExport, export_mfa_bypassesfrom ..metrics import HUB_API_AUTH_COUNTER@@ -38,10 +37,6 @@ def posthog_account_exists(*, user_uuid: str | None = None, organization_id: strreturn has_posthog_account(user_uuid=user_uuid, organization_id=organization_id)-def mfa_bypasses() -> MfaExport:- return export_mfa_bypasses()--def token_allows(claims: Mapping[str, Any] | None, op: str) -> bool:return claims_allow(claims, op)diff --git a/products/security/backend/logic/mfa_export.py b/products/security/backend/logic/mfa_export.pydeleted file mode 100644index 4b818bf4285d..000000000000--- a/products/security/backend/logic/mfa_export.py+++ /dev/null@@ -1,37 +0,0 @@-"""Reads the legacy Redis MFA bypasses for the hub's one-time import. Deleted at cut-over."""--from datetime import UTC, datetime, timedelta--from posthog.dataclasses import frozen-from posthog.helpers.two_factor_session import (- CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY,- get_code_based_verification_global_disable,-)-from posthog.redis import get_client---@frozen-class GlobalBypass:- reason: str- actor: str | None- expires_at: datetime---@frozen-class MfaExport:- emails: tuple[str, ...]- global_bypass: GlobalBypass | None---def export_mfa_bypasses() -> MfaExport:- members = get_client().smembers(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY)- emails = tuple(sorted(m.decode() if isinstance(m, bytes) else str(m) for m in members))- state = get_code_based_verification_global_disable()- global_bypass = None- if state and state.get("expires_in_seconds"):- global_bypass = GlobalBypass(- reason=str(state.get("reason", "")),- actor=state.get("disabled_by"),- expires_at=datetime.now(UTC) + timedelta(seconds=int(state["expires_in_seconds"])),- )- return MfaExport(emails=emails, global_bypass=global_bypass)diff --git a/products/security/backend/presentation/hub_api.py b/products/security/backend/presentation/hub_api.pyindex 39115d3e17fb..c750ead6d7ed 100644--- a/products/security/backend/presentation/hub_api.py+++ b/products/security/backend/presentation/hub_api.py@@ -26,7 +26,6 @@ from ..facade.hub import (INTERNAL_PURPOSE,count_accounts,count_org_members,- mfa_bypasses,posthog_account_exists,record_call,resolve,@@ -36,7 +35,6 @@ from ..facade.temporal import start_sync_nowfrom .serializers import (CountAccountsRequestSerializer,CountResponseSerializer,- MfaExportResponseSerializer,OrgMemberCountRequestSerializer,OrgMemberCountResponseSerializer,PosthogMembershipRequestSerializer,@@ -157,20 +155,10 @@ class SyncNowView(_HubView):return Response(status=status.HTTP_202_ACCEPTED)-class MfaBypassExportView(_HubView):- op = "mfa_bypass:export"-- @extend_schema(exclude=True)- def post(self, request: Request) -> Response:- exported = mfa_bypasses()- return Response(MfaExportResponseSerializer(exported).data)--urlpatterns = [path("resolve/", csrf_exempt(ResolveView.as_view())),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("sync-now/", csrf_exempt(SyncNowView.as_view())),- path("mfa-bypass-export/", csrf_exempt(MfaBypassExportView.as_view())),]diff --git a/products/security/backend/presentation/serializers.py b/products/security/backend/presentation/serializers.pyindex 2acacd90a375..693fea81f723 100644--- a/products/security/backend/presentation/serializers.py+++ b/products/security/backend/presentation/serializers.py@@ -1,7 +1,5 @@"""DRF serializers for security."""-from typing import Any-from rest_framework import serializers@@ -70,20 +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 GlobalBypassSerializer(serializers.Serializer):- reason = serializers.CharField(help_text="Why the global bypass was set.")- actor = serializers.CharField(allow_null=True, help_text="Who set it.")- expires_at = serializers.DateTimeField(help_text="When it expires.")---class MfaExportResponseSerializer(serializers.Serializer):- emails = serializers.ListField(child=serializers.CharField(), help_text="Addresses on the legacy bypass list.")-- def __init__(self, *args: Any, **kwargs: Any) -> None:- super().__init__(*args, **kwargs)- # "global" is a keyword, so this field cannot be declared in the class body.- self.fields["global"] = GlobalBypassSerializer(- source="global_bypass", allow_null=True, help_text="The global switch, when one is set."- )diff --git a/products/security/backend/tests/test_email_code_call_site.py b/products/security/backend/tests/test_email_code_call_site.pyindex 18bd9d3de789..ee48de3bcb80 100644--- a/products/security/backend/tests/test_email_code_call_site.py+++ b/products/security/backend/tests/test_email_code_call_site.py@@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCasefrom posthog.helpers.email_utils import ESPSuppressionResult-from posthog.helpers.two_factor_session import CodeBasedVerifier, add_code_based_verification_bypass+from posthog.helpers.two_factor_session import CodeBasedVerifierfrom products.security.backend.tests.helpers import exempt_rule, seed_rules@@ -47,8 +47,3 @@ class TestEmailCodeCallSite(SimpleTestCase):def test_expired_everyone_rule_requires_the_code(self, *_mocks: MagicMock) -> None:seed_rules(exempt_rule(targetType="everyone", targetValue="", expiresAt="2020-01-01T00:00:00Z"))assert self._should_send("[email protected]") is True-- def test_legacy_redis_bypass_still_works(self, *_mocks: MagicMock) -> None:- seed_rules()- add_code_based_verification_bypass("[email protected]")- assert self._should_send("[email protected]") is Falsediff --git a/products/security/backend/tests/test_hub_api.py b/products/security/backend/tests/test_hub_api.pyindex 59f04015a542..1714f4d2762a 100644--- a/products/security/backend/tests/test_hub_api.py+++ b/products/security/backend/tests/test_hub_api.py@@ -11,10 +11,6 @@ import jwt as pyjwtfrom parameterized import parameterizedfrom rest_framework.test import APIClient-from posthog.helpers.two_factor_session import (- add_code_based_verification_bypass,- set_code_based_verification_global_disable,-)from posthog.models import UserSECRET = "in-us"@@ -111,20 +107,6 @@ class TestHubApi(BaseTest):def test_sync_now_answers_503_when_temporal_is_unreachable(self, start: MagicMock) -> None:assert self.post("sync-now", {}, "rules:sync_now").status_code == 503- def test_mfa_export(self) -> None:- add_code_based_verification_bypass("[email protected]")- set_code_based_verification_global_disable(- reason="email outage", ttl_seconds=3600, disabled_by="[email protected]"- )- body = self.post("mfa-bypass-export", {}, "mfa_bypass:export").json()- assert body["emails"] == ["[email protected]"]- assert body["global"]["reason"] == "email outage"- assert body["global"]["actor"] == "[email protected]"- assert body["global"]["expires_at"].endswith("Z")-- def test_mfa_export_without_a_global_switch(self) -> None:- assert self.post("mfa-bypass-export", {}, "mfa_bypass:export").json() == {"emails": [], "global": None}-@parameterized.expand([("no token", None, {}, 401),