: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
fix(auth): unblock passkey users in 2fa-enforced orgs (#60503)
Alex Lider8e0e6fd47a23
diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 62ac1bcf6afb..30392533d3d0 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -605,6 +605,11 @@ class InviteSignupSerializer(serializers.Serializer):verified=True,label="Passkey",)+ # Treat the passkey as the user's 2FA factor when the org enforces 2FA. Otherwise+ # they land behind an undismissable setup modal that only offers TOTP enrollment+ if invite.organization.enforce_2fa and not user.passkeys_enabled_for_2fa:+ user.passkeys_enabled_for_2fa = True+ user.save(update_fields=["passkeys_enabled_for_2fa"])if is_new_user:verify_email_or_login(self.context["request"], user)diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 8f7b80ce9e85..d8f63cbe1bb5 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -2867,6 +2867,66 @@ class TestInviteSignupAPI(APIBaseTest):self.assertIsNone(session.get(WEBAUTHN_SIGNUP_EMAIL_KEY))self.assertIsNone(session.get(WEBAUTHN_SIGNUP_USER_UUID_KEY))+ @parameterized.expand(+ [+ ("org_enforces_2fa", True, True),+ ("org_does_not_enforce_2fa", False, False),+ ]+ )+ def test_passkey_invite_signup_passkeys_enabled_for_2fa(+ self, _name: str, org_enforce_2fa: bool, expected_passkeys_enabled_for_2fa: bool+ ):+ """+ Passkey signups into orgs that enforce 2FA must auto-enable the passkey as the 2FA factor.+ Otherwise the user lands behind the undismissable 2FA setup modal that only offers TOTP —+ which platform passkeys (macOS/iOS) cannot accept.+ """+ from django.contrib.sessions.backends.db import SessionStore++ from webauthn.helpers import bytes_to_base64url++ from posthog.api.webauthn import (+ WEBAUTHN_SIGNUP_CREDENTIAL_KEY,+ WEBAUTHN_SIGNUP_EMAIL_KEY,+ WEBAUTHN_SIGNUP_USER_UUID_KEY,+ )++ suffix = "enforced" if org_enforce_2fa else "unenforced"+ target_email = f"passkey_invite_{suffix}@posthog.com"+ self.organization.enforce_2fa = org_enforce_2fa+ self.organization.save(update_fields=["enforce_2fa"])++ invite: OrganizationInvite = OrganizationInvite.objects.create(+ target_email=target_email, organization=self.organization+ )++ # APIBaseTest leaves self.client authenticated as self.user, which would push the flow+ # down the "already authenticated" branch and skip new-user creation entirely.+ self.client.logout()++ session = SessionStore()+ session[WEBAUTHN_SIGNUP_EMAIL_KEY] = target_email+ session[WEBAUTHN_SIGNUP_USER_UUID_KEY] = str(uuid.uuid4())+ session[WEBAUTHN_SIGNUP_CREDENTIAL_KEY] = {+ "credential_id": bytes_to_base64url(f"cred-{suffix}".encode()),+ "public_key": bytes_to_base64url(f"pk-{suffix}".encode()),+ "algorithm": -7,+ "sign_count": 0,+ "transports": ["internal"],+ }+ session.create()+ self.client.cookies["sessionid"] = session.session_key or ""++ response = self.client.post(+ f"/api/signup/{invite.id}/",+ {"first_name": "Passkey", "last_name": "Invite"},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ user = User.objects.get(email=target_email)+ self.assertEqual(WebauthnCredential.objects.filter(user=user, verified=True).count(), 1)+ self.assertEqual(user.passkeys_enabled_for_2fa, expected_passkeys_enabled_for_2fa)+class TestSignupPrecheckPendingInvite(APIBaseTest):def setUp(self):diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex bda8d3289e8d..53beff218dfc 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2657,6 +2657,51 @@ class TestUserTwoFactor(APIBaseTest):},)+ @parameterized.expand(+ [+ # name, has_totp, passkey_state, passkeys_enabled_for_2fa, expected_is_2fa_enabled+ ("no_factor", False, None, False, False),+ ("totp_only", True, None, False, True),+ ("passkey_enabled_for_2fa", False, "verified", True, True),+ ("passkey_present_but_disabled_for_2fa", False, "verified", False, False),+ ("unverified_passkey_enabled_for_2fa", False, "unverified", True, False),+ ]+ )+ def test_user_me_is_2fa_enabled(+ self,+ _name: str,+ has_totp: bool,+ passkey_state: str | None,+ passkeys_enabled_for_2fa: bool,+ expected_is_2fa_enabled: bool,+ ):+ """+ /api/users/@me/.is_2fa_enabled must reflect passkey-2FA, not only TOTP — otherwise the+ frontend keeps reopening the enforce-2FA setup modal even after the user has a passkey+ configured as their second factor.+ """+ from posthog.models.webauthn_credential import WebauthnCredential++ if has_totp:+ TOTPDevice.objects.create(user=self.user, name="default", confirmed=True)+ if passkey_state is not None:+ WebauthnCredential.objects.create(+ user=self.user,+ credential_id=b"cred",+ label="Test Passkey",+ public_key=b"pk",+ algorithm=-7,+ counter=0,+ transports=["internal"],+ verified=(passkey_state == "verified"),+ )+ self.user.passkeys_enabled_for_2fa = passkeys_enabled_for_2fa+ self.user.save(update_fields=["passkeys_enabled_for_2fa"])++ response = self.client.get("/api/users/@me/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["is_2fa_enabled"], expected_is_2fa_enabled)+@patch("posthog.api.user.default_device")def test_two_factor_backup_codes_generation(self, mock_default_device):# Mock TOTP device to simulate 2FA being enableddiff --git a/posthog/api/user.py b/posthog/api/user.pyindex 2db0376c8c11..ee42858fdc13 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -389,7 +389,9 @@ class UserSerializer(serializers.ModelSerializer):@tracer.start_as_current_span("user_serializer.is_2fa_enabled")def get_is_2fa_enabled(self, instance: User) -> bool:- return default_device(instance) is not None+ has_totp_device = default_device(instance) is not None+ has_passkey_2fa = bool(instance.passkeys_enabled_for_2fa) and has_passkeys(instance)+ return has_totp_device or has_passkey_2fa@tracer.start_as_current_span("user_serializer.has_sso_enforcement")def get_has_sso_enforcement(self, instance: User) -> bool: