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.

fix(auth): give passwordless users a way out when passkey re-auth fails (#129560)

Rafael Audibert5911d5a56630
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/SetPasswordLinkPrompt.tsx b/frontend/src/lib/components/TimeSensitiveAuthentication/SetPasswordLinkPrompt.tsx
new file mode 100644
index 000000000000..f71633ca08a2
--- /dev/null
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/SetPasswordLinkPrompt.tsx
@@ -0,0 +1,32 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { timeSensitiveAuthenticationLogic } from './timeSensitiveAuthenticationLogic'
+
+export function SetPasswordLinkPrompt(): JSX.Element {
+ const { setPasswordLinkSentTo, setPasswordLinkSentToLoading } = useValues(timeSensitiveAuthenticationLogic)
+ const { sendSetPasswordLink } = useActions(timeSensitiveAuthenticationLogic)
+
+ return (
+ <div className="mt-4 flex justify-center text-center text-secondary">
+ {setPasswordLinkSentTo ? (
+ <p className="m-0">
+ We sent a link to <b>{setPasswordLinkSentTo}</b>. Open it to set a password, then sign in with your
+ new password.
+ </p>
+ ) : (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ htmlType="button"
+ loading={setPasswordLinkSentToLoading}
+ onClick={sendSetPasswordLink}
+ data-attr="reauth-set-password-link"
+ >
+ Can't use your passkey? Email me a link to set a password
+ </LemonButton>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx b/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx
index 641f71d45e77..960fd30301a8 100644
--- a/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx
@@ -8,6 +8,7 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { SSOEnforcedLoginButton, SocialLoginButtons } from '../SocialLoginButton/SocialLoginButton'
+import { SetPasswordLinkPrompt } from './SetPasswordLinkPrompt'
import { timeSensitiveAuthenticationLogic } from './timeSensitiveAuthenticationLogic'
export function TimeSensitiveAuthenticationModal(): JSX.Element {
@@ -27,6 +28,7 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {
const ssoEnforcement = precheckResponse?.sso_enforcement
const showPassword = !ssoEnforcement && user?.has_password
+ const showSetPasswordLink = !ssoEnforcement && user?.has_password === false
const extraQueryParams = {
next: location.href.replace(location.origin, ''),
@@ -174,6 +176,7 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {
) : null}
</div>
) : null}
+ {showSetPasswordLink ? <SetPasswordLinkPrompt /> : null}
{precheckResponseLoading && <SpinnerOverlay />}
</LemonModal>
)
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts
index 92bd2939c2d5..14dfa52b0151 100644
--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts
@@ -10,6 +10,7 @@ import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
import { userLogic } from 'scenes/userLogic'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { timeSensitiveAuthenticationLogic } from './timeSensitiveAuthenticationLogic'
@@ -172,6 +173,27 @@ describe('timeSensitiveAuthenticationLogic', () => {
await expectLogic(logic).toMatchValues({ showAuthenticationModal: false })
})
+
+ it('should email the signed-in user a link to set a password', async () => {
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, has_password: false })
+ const resetRequests: unknown[] = []
+ useMocks({
+ post: {
+ '/api/reset/': async ({ request }) => {
+ resetRequests.push(await request.json())
+ return [204]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.sendSetPasswordLink()
+ })
+ .toDispatchActions(['sendSetPasswordLinkSuccess'])
+ .toMatchValues({ setPasswordLinkSentTo: MOCK_DEFAULT_USER.email })
+
+ expect(resetRequests).toEqual([{ email: MOCK_DEFAULT_USER.email }])
+ })
})
describe('SSO re-authentication in a popup', () => {
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
index 304f9d3920f1..716563b140bd 100644
--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
@@ -65,6 +65,8 @@ export interface timeSensitiveAuthenticationLogicValues {
reauthenticationTouches: Record<string, boolean>
reauthenticationValidationErrors: DeepPartialMap<ReauthenticationForm, ValidationErrorType>
sensitiveSessionExpiresAt: Dayjs
+ setPasswordLinkSentTo: string | null
+ setPasswordLinkSentToLoading: boolean
showAuthenticationModal: boolean
showReauthenticationErrors: boolean
totpAvailable: boolean
@@ -148,6 +150,27 @@ export interface timeSensitiveAuthenticationLogicActions {
resetReauthentication: (values?: ReauthenticationForm) => {
values?: ReauthenticationForm
}
+ sendSetPasswordLink: () => {
+ value: true
+ }
+ sendSetPasswordLinkFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ sendSetPasswordLinkSuccess: (
+ setPasswordLinkSentTo: string | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ setPasswordLinkSentTo: string | null
+ payload?: {
+ value: true
+ }
+ }
setDismissedReauthentication: (value: boolean) => {
value: boolean
}
@@ -247,6 +270,7 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationL
ssoReauthenticationFinished: (attempt: string, errorCode: string | null) => ({ attempt, errorCode }),
beginPasskey2FA: true,
checkPasskeysAvailable: true,
+ sendSetPasswordLink: true,
setTotpAvailable: (available: boolean) => ({ available }),
}),
reducers({
@@ -316,6 +340,24 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationL
},
},
],
+ setPasswordLinkSentTo: [
+ null as string | null,
+ {
+ sendSetPasswordLink: async (_, breakpoint) => {
+ breakpoint()
+ const email = values.user?.email
+ if (!email) {
+ return null
+ }
+ // On an account without a password, the reset link sets its first password. The reset page
+ // works while signed in, so this is the way out when the user's passkey stops working.
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
+ await api.create('api/reset/', { email })
+ posthog.capture('reauthentication_set_password_link_sent')
+ return email
+ },
+ },
+ ],
passkeysAvailable: [
false as boolean,
{
diff --git a/posthog/api/test/test_webauthn.py b/posthog/api/test/test_webauthn.py
index 561e09e69cb3..bcd76ee43434 100644
--- a/posthog/api/test/test_webauthn.py
+++ b/posthog/api/test/test_webauthn.py
@@ -13,7 +13,13 @@ from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed
from webauthn.helpers import bytes_to_base64url
-from posthog.api.webauthn import WEBAUTHN_REGISTRATION_CHALLENGE_KEY, WebAuthnLoginViewSet, user_uuid_to_handle
+from posthog.api.webauthn import (
+ PASSKEY_NOT_REGISTERED_ERROR,
+ PASSKEY_NOT_VERIFIED_ERROR,
+ WEBAUTHN_REGISTRATION_CHALLENGE_KEY,
+ WebAuthnLoginViewSet,
+ user_uuid_to_handle,
+)
from posthog.auth import WebauthnBackend
from posthog.models import Organization, User
from posthog.models.identity_provider_config import IdentityProviderConfig
@@ -339,36 +345,48 @@ class TestWebAuthnLogin(APIBaseTest):
mock_is_email_available.assert_called_once()
mock_send_email_verification.assert_called_once_with(self.user)
+ @parameterized.expand(
+ [
+ ("unverified_credential", False, b"test-credential-id", False, PASSKEY_NOT_REGISTERED_ERROR),
+ ("unknown_credential", True, b"removed-credential-id", False, PASSKEY_NOT_REGISTERED_ERROR),
+ ("failed_assertion", True, b"test-credential-id", True, PASSKEY_NOT_VERIFIED_ERROR),
+ ]
+ )
@patch("posthog.auth.verify_passkey_authentication_response")
- def test_login_with_unverified_credential_fails(self, mock_verify):
- from webauthn.helpers import bytes_to_base64url
-
- from posthog.api.webauthn import user_uuid_to_handle
-
- self.credential.verified = False
+ def test_login_failure_names_the_cause(
+ self,
+ _name: str,
+ credential_verified: bool,
+ presented_credential_id: bytes,
+ assertion_fails: bool,
+ expected_error: str,
+ mock_verify,
+ ):
+ self.credential.verified = credential_verified
self.credential.save()
+ mock_verify.return_value = MagicMock(new_sign_count=1)
+ if assertion_fails:
+ mock_verify.side_effect = Exception("signature mismatch")
self.client.post("/api/webauthn/login/begin/")
-
- user_handle = user_uuid_to_handle(self.user.uuid)
-
response = self.client.post(
"/api/webauthn/login/complete/",
{
- "id": bytes_to_base64url(self.credential.credential_id),
- "rawId": bytes_to_base64url(self.credential.credential_id),
+ "id": bytes_to_base64url(presented_credential_id),
+ "rawId": bytes_to_base64url(presented_credential_id),
"type": "public-key",
"response": {
"authenticatorData": "data",
"clientDataJSON": "data",
"signature": "sig",
- "userHandle": bytes_to_base64url(user_handle),
+ "userHandle": bytes_to_base64url(user_uuid_to_handle(self.user.uuid)),
},
},
format="json",
)
+
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("authentication failed", response.json()["error"].lower())
+ self.assertEqual(response.json()["error"], expected_error)
@patch("posthog.auth.verify_passkey_authentication_response")
def test_login_rejects_spoofed_user_handle(self, mock_verify):
diff --git a/posthog/api/webauthn.py b/posthog/api/webauthn.py
index 07bc810a3b69..c0516c245402 100644
--- a/posthog/api/webauthn.py
+++ b/posthog/api/webauthn.py
@@ -53,6 +53,12 @@ WEBAUTHN_SIGNUP_EMAIL_KEY = "webauthn_signup_email"
WEBAUTHN_SIGNUP_CREDENTIAL_KEY = "webauthn_signup_passkey_credential"
WEBAUTHN_SIGNUP_USER_UUID_KEY = "webauthn_signup_user_uuid"
WEBAUTHN_LOGIN_CHALLENGE_KEY = "webauthn_login_challenge"
+
+PASSKEY_NOT_REGISTERED_ERROR = (
+ "This passkey isn't registered with PostHog. It may have been removed from your account. "
+ "Choose another passkey, or sign in another way."
+)
+PASSKEY_NOT_VERIFIED_ERROR = "We couldn't verify this passkey. Try again, or sign in another way."
WEBAUTHN_2FA_CHALLENGE_KEY = "webauthn_2fa_challenge"
@@ -356,7 +362,9 @@ class WebAuthnLoginViewSet(viewsets.ViewSet):
# failures against the claimed identity is acceptable for rate limiting.
claimed_user = self._extract_user_from_user_handle(user_handle_b64)
return self._handle_authentication_failure(request, claimed_user) or _login_error(
- "Authentication failed. Please check your passkey and try again."
+ PASSKEY_NOT_VERIFIED_ERROR
+ if self._is_registered_credential(claimed_user, credential_id)
+ else PASSKEY_NOT_REGISTERED_ERROR
)
# Cast to our User model — WebauthnBackend.authenticate() always returns
@@ -414,6 +422,19 @@ class WebAuthnLoginViewSet(viewsets.ViewSet):
return None
+ def _is_registered_credential(self, claimed_user: User | None, credential_id: str) -> bool:
+ # Scoped to the user the unsigned userHandle names, so the lookup uses the (user, credential_id)
+ # index. A spoofed handle only changes which of two refusal messages the caller sees.
+ if not claimed_user:
+ return False
+ try:
+ credential_id_bytes = base64url_to_bytes(credential_id)
+ except Exception:
+ return False
+ return WebauthnCredential.objects.filter(
+ user=claimed_user, credential_id=credential_id_bytes, verified=True
+ ).exists()
+
def _extract_user_from_user_handle(self, user_handle_b64: str) -> User | None:
"""Extract user from base64url-encoded userHandle (UUID bytes)."""
try: