: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(auth): add admin switch to disable email MFA globally (#59899)
Yasen1492615f90e3
diff --git a/ee/urls.py b/ee/urls.pyindex 3880f9f4fd2a..72469d161bd8 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -121,7 +121,11 @@ if settings.ADMIN_PORTAL_ENABLED:backfill_precalculated_person_properties_view,)from posthog.admin.admins.distinct_id_usage_admin import distinct_id_usage_view- from posthog.admin.admins.email_mfa_bypass_admin import EmailMFABypassViewSet, email_mfa_bypass_view+ from posthog.admin.admins.email_mfa_bypass_admin import (+ EmailMFABypassViewSet,+ EmailMFAGlobalDisableViewSet,+ email_mfa_bypass_view,+ )from posthog.admin.admins.health_check_admin import (health_check_list_view,health_check_runs_fragment_view,@@ -176,6 +180,11 @@ if settings.ADMIN_PORTAL_ENABLED:EmailMFABypassViewSet.as_view({"delete": "destroy"}),name="email-mfa-bypass-api-detail",),+ path(+ "admin/api/email-mfa-global-disable/",+ EmailMFAGlobalDisableViewSet.as_view({"get": "list", "post": "create", "delete": "destroy"}),+ name="email-mfa-global-disable-api",+ ),path("admin/resave-cohorts/",admin.site.admin_view(resave_cohorts_view),diff --git a/posthog/admin/admins/email_mfa_bypass_admin.py b/posthog/admin/admins/email_mfa_bypass_admin.pyindex 02f436915d1a..9fd566bdfc2f 100644--- a/posthog/admin/admins/email_mfa_bypass_admin.py+++ b/posthog/admin/admins/email_mfa_bypass_admin.py@@ -1,3 +1,5 @@+from typing import cast+from django.contrib import adminfrom django.shortcuts import render@@ -6,7 +8,16 @@ from rest_framework.permissions import IsAdminUserfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.helpers.two_factor_session import EMAIL_MFA_BYPASS_REDIS_KEY, add_email_mfa_bypass, remove_email_mfa_bypass+from posthog.helpers.two_factor_session import (+ EMAIL_MFA_BYPASS_REDIS_KEY,+ MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,+ add_email_mfa_bypass,+ clear_email_mfa_global_disable,+ get_email_mfa_global_disable,+ remove_email_mfa_bypass,+ set_email_mfa_global_disable,+)+from posthog.models.user import Userfrom posthog.redis import get_client@@ -14,6 +25,39 @@ class EmailMFABypassEmailSerializer(serializers.Serializer):email = serializers.EmailField(help_text="Email address to bypass email MFA verification")+class EmailMFAGlobalDisableSerializer(serializers.Serializer):+ reason = serializers.CharField(allow_blank=False, help_text="Why email MFA is being disabled globally")+ ttl_seconds = serializers.IntegerField(+ min_value=1,+ max_value=MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,+ help_text="How long the disable lasts, in seconds (max 7 days)",+ )+++class EmailMFAGlobalDisableViewSet(viewsets.ViewSet):+ """Completely disable email MFA verification for all users, with a required reason and TTL."""++ permission_classes = [IsAdminUser]++ def list(self, request: Request) -> Response:+ state = get_email_mfa_global_disable()+ return Response({"disabled": state is not None, "state": state})++ def create(self, request: Request) -> Response:+ serializer = EmailMFAGlobalDisableSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ set_email_mfa_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_email_mfa_global_disable()}, status=status.HTTP_201_CREATED)++ def destroy(self, request: Request) -> Response:+ clear_email_mfa_global_disable()+ return Response(status=status.HTTP_204_NO_CONTENT)++class EmailMFABypassViewSet(viewsets.ViewSet):permission_classes = [IsAdminUser]@@ -45,6 +89,7 @@ def email_mfa_bypass_view(request):context = {"bypass_emails": bypass_emails,+ "global_disable": get_email_mfa_global_disable(),"title": "Email MFA bypass","has_view_permission": True,"site_title": admin.site.site_title,diff --git a/posthog/admin/test_email_mfa_global_disable_admin.py b/posthog/admin/test_email_mfa_global_disable_admin.pynew file mode 100644index 000000000000..ce28e6dc370b--- /dev/null+++ b/posthog/admin/test_email_mfa_global_disable_admin.py@@ -0,0 +1,79 @@+from posthog.test.base import APIBaseTest++from rest_framework import status+from rest_framework.test import APIRequestFactory, force_authenticate++from posthog.admin.admins.email_mfa_bypass_admin import EmailMFAGlobalDisableViewSet+from posthog.helpers.two_factor_session import (+ MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,+ clear_email_mfa_global_disable,+ is_email_mfa_globally_disabled,+)+++class TestEmailMFAGlobalDisableAdmin(APIBaseTest):+ def setUp(self):+ super().setUp()+ clear_email_mfa_global_disable()+ self.factory = APIRequestFactory()++ def tearDown(self):+ clear_email_mfa_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/email-mfa-global-disable/")+ force_authenticate(request, user=self.user)+ response = EmailMFAGlobalDisableViewSet.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/email-mfa-global-disable/", {"reason": "email outage", "ttl_seconds": 3600}, format="json"+ )+ force_authenticate(request, user=self.user)+ response = EmailMFAGlobalDisableViewSet.as_view({"post": "create"})(request)+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertTrue(is_email_mfa_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/email-mfa-global-disable/")+ force_authenticate(request, user=self.user)+ response = EmailMFAGlobalDisableViewSet.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/email-mfa-global-disable/")+ force_authenticate(request, user=self.user)+ response = EmailMFAGlobalDisableViewSet.as_view({"delete": "destroy"})(request)+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(is_email_mfa_globally_disabled())++ def test_reason_is_required(self):+ self._make_staff()+ request = self.factory.post(+ "/admin/api/email-mfa-global-disable/", {"reason": "", "ttl_seconds": 3600}, format="json"+ )+ force_authenticate(request, user=self.user)+ response = EmailMFAGlobalDisableViewSet.as_view({"post": "create"})(request)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(is_email_mfa_globally_disabled())++ def test_ttl_cap_is_enforced(self):+ self._make_staff()+ request = self.factory.post(+ "/admin/api/email-mfa-global-disable/",+ {"reason": "too long", "ttl_seconds": MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS + 1},+ format="json",+ )+ force_authenticate(request, user=self.user)+ response = EmailMFAGlobalDisableViewSet.as_view({"post": "create"})(request)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(is_email_mfa_globally_disabled())diff --git a/posthog/helpers/tests/test_two_factor_session.py b/posthog/helpers/tests/test_two_factor_session.pyindex 0530b9dc75f7..a98c94e79083 100644--- a/posthog/helpers/tests/test_two_factor_session.py+++ b/posthog/helpers/tests/test_two_factor_session.py@@ -5,8 +5,18 @@ 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 EmailMFACheckResult, EmailMFAVerifier+from posthog.helpers.two_factor_session import (+ MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,+ EmailMFACheckResult,+ EmailMFAVerifier,+ clear_email_mfa_global_disable,+ get_email_mfa_global_disable,+ is_email_mfa_globally_disabled,+ set_email_mfa_global_disable,+)@pytest.mark.disable_mock_email_mfa_verifier@@ -199,3 +209,70 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "email_mfa_bypassed_due_to_suppression")self.assertEqual(call_kwargs["properties"]["reason"], ESPSuppressionReason.NO_EMAIL_HTTP_SERVICE)+++class TestEmailMFAGlobalDisable(SimpleTestCase):+ def setUp(self):+ clear_email_mfa_global_disable()++ def tearDown(self):+ clear_email_mfa_global_disable()++ def test_not_disabled_by_default(self):+ self.assertFalse(is_email_mfa_globally_disabled())+ self.assertIsNone(get_email_mfa_global_disable())++ def test_set_get_clear_round_trip(self):+ set_email_mfa_global_disable(reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]")++ self.assertTrue(is_email_mfa_globally_disabled())+ state = get_email_mfa_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_email_mfa_global_disable()+ self.assertFalse(is_email_mfa_globally_disabled())+ self.assertIsNone(get_email_mfa_global_disable())++ def test_reason_is_stripped_and_required(self):+ with self.assertRaises(ValueError):+ set_email_mfa_global_disable(reason=" ", ttl_seconds=3600, disabled_by="[email protected]")+ self.assertFalse(is_email_mfa_globally_disabled())++ @parameterized.expand(+ [+ ("zero", 0),+ ("negative", -1),+ ("over_max", MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS + 1),+ ]+ )+ def test_invalid_ttl_rejected(self, _name, ttl_seconds):+ with self.assertRaises(ValueError):+ set_email_mfa_global_disable(reason="reason", ttl_seconds=ttl_seconds, disabled_by="[email protected]")+ self.assertFalse(is_email_mfa_globally_disabled())++ def test_max_ttl_accepted(self):+ set_email_mfa_global_disable(+ reason="reason", ttl_seconds=MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS, disabled_by="[email protected]"+ )+ self.assertTrue(is_email_mfa_globally_disabled())++ @pytest.mark.disable_mock_email_mfa_verifier+ def test_global_disable_skips_email_mfa(self):+ user = MagicMock()+ user.pk = 1+ user.email = "[email protected]"++ set_email_mfa_global_disable(reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]")+ result = EmailMFAVerifier().should_send_email_mfa_verification(user)+ self.assertEqual(result, EmailMFACheckResult(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_email_mfa_globally_disabled())+ self.assertIsNone(get_email_mfa_global_disable())diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex ed4dcaff14f9..5dc4483b78f8 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -1,3 +1,4 @@+import jsonimport timeimport datetimefrom dataclasses import dataclass@@ -40,6 +41,61 @@ def remove_email_mfa_bypass(email: str) -> None:get_client().srem(EMAIL_MFA_BYPASS_REDIS_KEY, email.lower())+# Global kill-switch: when this Redis key is present, email MFA verification is skipped for every+# user (e.g. while transactional email delivery is down and the verification link 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.+EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY = "email_mfa_global_disable"+MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days+++def is_email_mfa_globally_disabled() -> bool:+ # Fail closed: if Redis is unreachable, keep email MFA 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(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY))+ except Exception:+ mfa_logger.exception("Failed to read email MFA global disable flag; keeping email MFA enforced")+ return False+++def get_email_mfa_global_disable() -> Optional[dict]:+ try:+ client = get_client()+ raw = client.get(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY)+ if not raw:+ return None+ data = json.loads(raw)+ ttl = client.ttl(EMAIL_MFA_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 email MFA global disable state")+ return None+++def set_email_mfa_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 email MFA.")+ if not 0 < ttl_seconds <= MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS:+ raise ValueError(+ f"TTL must be between 1 second and {MAX_EMAIL_MFA_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(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY, payload, ex=ttl_seconds)+++def clear_email_mfa_global_disable() -> None:+ get_client().delete(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY)++def has_passkeys(user: User) -> bool:"""Returns True if the user has any verified passkeys, False otherwise.@@ -329,6 +385,9 @@ class EmailMFAVerifier:)def should_send_email_mfa_verification(self, user: User) -> EmailMFACheckResult:+ if is_email_mfa_globally_disabled():+ return EmailMFACheckResult(should_send=False)+if is_dev_mode() and not settings.TEST:return EmailMFACheckResult(should_send=False)diff --git a/posthog/templates/admin/email_mfa_bypass.html b/posthog/templates/admin/email_mfa_bypass.htmlindex a7363cf528d6..1bdb07f54ed1 100644--- a/posthog/templates/admin/email_mfa_bypass.html+++ b/posthog/templates/admin/email_mfa_bypass.html@@ -23,6 +23,48 @@<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>@@ -157,5 +199,69 @@ document.getElementById('email-list-body').addEventListener('click', function(e)const row = btn.closest('tr');if (row) removeEmail(row.dataset.email);});++// --- Global email MFA disable ---+const GLOBAL_API = '/admin/api/email-mfa-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 %}