: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): show the required sso method after a passkey login is refused (#120262)
Alex Lider6ba83a26141d
diff --git a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsxindex 8a818984b681..09c55e3fbd68 100644--- a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx+++ b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx@@ -1,5 +1,8 @@+import { SSO_PROVIDER_NAMES } from 'lib/constants'import { Link } from 'lib/lemon-ui/Link'+import { SSOProvider } from '~/types'+// Login error copy shared by the auth login variants and the exporter login screen.export const ERROR_MESSAGES: Record<string, string | JSX.Element> = {no_new_organizations:@@ -43,3 +46,11 @@ export const ERROR_MESSAGES: Record<string, string | JSX.Element> = {access_blocked:"We couldn't sign you in. If you think this is a mistake, contact support and quote the code access_blocked.",}++// The server detail for `sso_enforced` holds the internal provider key, so the login form uses this copy instead+export function ssoEnforcedMessage(provider: SSOProvider | string | null | undefined): string {+ const providerName = provider ? SSO_PROVIDER_NAMES[provider as SSOProvider] : undefined+ return providerName+ ? `Your organization requires you to log in with ${providerName}.`+ : "Please log in with your organization's required SSO method."+}diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.test.tsindex 54ca96d14527..c2d2d040a3e2 100644--- a/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts@@ -2,6 +2,7 @@ import { browserSupportsWebAuthnAutofill, startAuthentication } from '@simplewebimport { expectLogic } from 'kea-test-utils'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'+import { loginLogic } from 'scenes/authentication/login/loginLogic'import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'import { useMocks } from '~/mocks/jest'@@ -158,4 +159,60 @@ describe('passkeyLogic', () => {expect(logic.values.isReauth).toBe(false)})})++ describe('SSO-enforced account', () => {+ let logic: ReturnType<typeof passkeyLogic.build>++ beforeEach(() => {+ ;(startAuthentication as jest.Mock).mockResolvedValue({ id: 'cred-1', response: {} })+ useMocks({+ get: { '/api/users/@me/': () => [200, {}] },+ post: {+ '/api/webauthn/login/begin/': () => [+ 200,+ {+ challenge: 'abc',+ timeout: 60000,+ rpId: 'localhost',+ allowCredentials: [],+ userVerification: 'required',+ },+ ],+ '/api/webauthn/login/complete/': () => [+ 400,+ {+ error: 'You can only login with SSO for this account.',+ code: 'sso_enforced',+ sso_enforcement: 'google-oauth2',+ email: '[email protected]',+ },+ ],+ '/api/login/precheck': () => [200, { sso_enforcement: 'google-oauth2', saml_available: false }],+ },+ })+ initKeaTests()+ logic = passkeyLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.clearAllMocks()+ })++ it('names the required provider and runs the precheck for the returned email', async () => {+ logic.actions.beginPasskeyLogin()+ await expectLogic(loginLogic).toDispatchActions(['precheckSuccess'])++ expect(loginLogic.values.generalError).toEqual({+ code: 'passkey_error',+ detail: 'Your organization requires you to log in with Google.',+ })+ expect(loginLogic.values.login.email).toBe('[email protected]')+ expect(loginLogic.values.precheckResponse).toMatchObject({+ email: '[email protected]',+ sso_enforcement: 'google-oauth2',+ })+ })+ })})diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.tsindex 8033c4531e37..4dbb11c04a2c 100644--- a/frontend/src/scenes/authentication/shared/passkeyLogic.ts+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.ts@@ -4,6 +4,7 @@ import {startAuthentication,} from '@simplewebauthn/browser'import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import type { FieldName } from 'kea-forms'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import posthog from 'posthog-js'@@ -13,6 +14,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { isWebKitBrowser } from 'lib/utils/dom'import { loginLogic, redirectAfterLogin } from 'scenes/authentication/login/loginLogic'+import { ssoEnforcedMessage } from 'scenes/authentication/shared/loginErrorMessages'import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -44,6 +46,23 @@ function routeToEmailVerification(e: unknown): boolean {return true}+// A discoverable passkey is picked before any email is typed, so an SSO-enforced account is only+// refused at the complete step. The response carries the account's email: prefill it and run the+// precheck, which swaps the password form for the required SSO button.+function showPasskeyLoginError(e: unknown, actions: passkeyLogicType['actions']): void {+ const { code, data } = (e ?? {}) as Record<string, any>+ if (code !== 'sso_enforced') {+ actions.setGeneralError('passkey_error', getPasskeyErrorMessage(e))+ return+ }+ // The code stays `passkey_error` so login telemetry keeps counting this as a passkey step.+ actions.setGeneralError('passkey_error', ssoEnforcedMessage(data?.sso_enforcement))+ if (data?.email) {+ actions.setLoginValue('email', data.email)+ actions.precheck({ email: data.email })+ }+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface passkeyLogicValues {allowCredentialsFromPrecheck: PublicKeyCredentialDescriptorJSON[]@@ -60,6 +79,10 @@ export interface passkeyLogicActions {resolveSensitiveAction: (outcome: 'failure' | 'success') => {outcome: 'failure' | 'success'} // apiStatusLogic+ precheck: (args_0: { autoAttempt?: boolean; email: string }) => {+ autoAttempt?: boolean+ email: string+ } // loginLogicsetGeneralError: (code: string,detail: string@@ -67,6 +90,13 @@ export interface passkeyLogicActions {code: stringdetail: string} // loginLogic+ setLoginValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ } // loginLogicloadUser: (resetOnFailure?: boolean | undefined) => {resetOnFailure: boolean | undefined} // userLogic@@ -114,7 +144,14 @@ export type passkeyLogicType = MakeLogicType<passkeyLogicValues, passkeyLogicActexport const passkeyLogic = kea<passkeyLogicType>([path(['scenes', 'authentication', 'shared', 'passkeyLogic']),connect(() => ({- actions: [loginLogic, ['setGeneralError'], apiStatusLogic, ['resolveSensitiveAction'], userLogic, ['loadUser']],+ actions: [+ loginLogic,+ ['setGeneralError', 'setLoginValue', 'precheck'],+ apiStatusLogic,+ ['resolveSensitiveAction'],+ userLogic,+ ['loadUser'],+ ],})),actions({beginPasskeyLogin: (@@ -207,7 +244,7 @@ export const passkeyLogic = kea<passkeyLogicType>([// continues on the verification page, not with a login error.throw e}- actions.setGeneralError('passkey_error', getPasskeyErrorMessage(e))+ showPasskeyLoginError(e, actions)throw e}},@@ -260,7 +297,7 @@ export const passkeyLogic = kea<passkeyLogicType>([// The autofill passkey prompt is routinely dismissed — the user types a password// instead, or navigates away. Swallow those; surface anything genuinely wrong.if (!isWebAuthnCancellation(e) && !routeToEmailVerification(e)) {- actions.setGeneralError('passkey_error', getPasskeyErrorMessage(e))+ showPasskeyLoginError(e, actions)}}},diff --git a/posthog/api/test/test_webauthn.py b/posthog/api/test/test_webauthn.pyindex 6e60a9c7221a..561e09e69cb3 100644--- a/posthog/api/test/test_webauthn.py+++ b/posthog/api/test/test_webauthn.py@@ -469,7 +469,11 @@ class TestWebAuthnLogin(APIBaseTest):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("SSO", response.json()["error"])+ body = response.json()+ self.assertIn("SSO", body["error"])+ self.assertEqual(body["code"], "sso_enforced")+ self.assertEqual(body["sso_enforcement"], "saml")+ self.assertEqual(body["email"], self.user.email)# Verify the user is NOT logged inme_response = self.client.get("/api/users/@me/")diff --git a/posthog/api/webauthn.py b/posthog/api/webauthn.pyindex 8497065015fe..07bc810a3b69 100644--- a/posthog/api/webauthn.py+++ b/posthog/api/webauthn.py@@ -427,8 +427,15 @@ class WebAuthnLoginViewSet(viewsets.ViewSet):"""Check SSO enforcement for the user. Returns SSO error response if enforced, None otherwise."""sso_enforcement = OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email)if sso_enforcement:+ # The assertion is already verified, so the email only goes back to its owner. The login+ # form needs it to run the precheck, because a discoverable passkey carries no typed email.return Response(- {"error": "You can only login with SSO for this account."},+ {+ "error": "You can only login with SSO for this account.",+ "code": "sso_enforced",+ "sso_enforcement": sso_enforcement,+ "email": user.email,+ },status=status.HTTP_400_BAD_REQUEST,)return None