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.

feat(auth): hide the password box for accounts with no password (#75015)

Reece Jonesfa7aba33fe12
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index 2e66ba1458fb..0fa00d31397d 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -67,7 +67,13 @@ class TestEELoginPrecheckAPI(APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
- {"sso_enforcement": "google-oauth2", "saml_available": False, "webauthn_credentials": []},
+ {
+ "sso_enforcement": "google-oauth2",
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
def test_login_precheck_with_unverified_domain(self):
@@ -84,7 +90,14 @@ class TestEELoginPrecheckAPI(APILicensedTest):
) # Note we didn't create a user that matches, only domain is matched
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": None, "saml_available": False, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
def test_login_precheck_with_inexistent_account(self):
@@ -100,7 +113,14 @@ class TestEELoginPrecheckAPI(APILicensedTest):
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": "github", "saml_available": False, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": "github",
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
def test_login_precheck_with_enforced_sso_but_improperly_configured_sso(self):
@@ -117,7 +137,14 @@ class TestEELoginPrecheckAPI(APILicensedTest):
) # Note Google OAuth is not configured
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": None, "saml_available": False, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
@@ -389,7 +416,16 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
"/api/login/precheck", {"email": "[email protected]"}
) # Note Google OAuth is not configured
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), {"sso_enforcement": None, "saml_available": True, "webauthn_credentials": []})
+ self.assertEqual(
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": True,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
+ )
# Initiate SAML flow
@@ -859,7 +895,14 @@ YotAcSbU3p5bzd11wpyebYHB"""
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": "saml", "saml_available": True, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": "saml",
+ "saml_available": True,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
def test_cannot_use_saml_without_enterprise_license(self):
@@ -874,7 +917,14 @@ YotAcSbU3p5bzd11wpyebYHB"""
response = self.client.post("/api/login/precheck", {"email": self.CONFIG_EMAIL})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": None, "saml_available": False, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
# Cannot start SAML flow - sso_login catches AuthFailed and redirects
diff --git a/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx b/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx
index 4fe24ef31646..77a9bd1185ae 100644
--- a/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx
+++ b/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx
@@ -1,6 +1,6 @@
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { SSO_PROVIDER_NAMES } from 'lib/constants'
import { LemonButton, LemonButtonWithoutSideActionProps } from 'lib/lemon-ui/LemonButton'
@@ -13,6 +13,7 @@ import { LoginMethod, SSOProvider } from '~/types'
import passkeyLogo from './passkey.svg'
import { SocialLoginIcon } from './SocialLoginIcon'
+import { getSocialLoginUrl } from './socialLoginUrl'
interface SocialLoginLinkProps {
provider: SSOProvider
@@ -23,15 +24,7 @@ interface SocialLoginLinkProps {
function SocialLoginLink({ provider, extraQueryParams, children }: SocialLoginLinkProps): JSX.Element {
const { searchParams } = useValues(router)
- const loginParams: Record<string, string> = { ...extraQueryParams }
- if (searchParams.next) {
- loginParams.next = searchParams.next
- }
- if (provider === 'saml') {
- // SAML-based login requires an extra param as technically we can support multiple SAML backends
- loginParams.idp = 'posthog_custom'
- }
- const loginUrl = combineUrl(`/login/${provider}/`, loginParams).url
+ const loginUrl = getSocialLoginUrl(provider, extraQueryParams, searchParams)
const iframed = window !== window.parent
return (
@@ -128,6 +121,15 @@ interface SocialLoginButtonsProps {
extraQueryParams?: Record<string, string>
lastUsedProvider?: LoginMethod
showPasskey?: boolean
+ /**
+ * Limit the rendered providers to this allowlist. Used when we know which providers a specific
+ * account can actually use, so we don't offer a button that would fail. `null`/omitted means
+ * "no restriction" — render everything the instance has configured.
+ *
+ * Note `'saml'` is never rendered here (it isn't in `available_social_auth_providers`); it goes
+ * through `SSOEnforcedLoginButton` instead.
+ */
+ restrictToProviders?: SSOProvider[] | null
}
export function SocialLoginButtons({
@@ -139,6 +141,7 @@ export function SocialLoginButtons({
bottomDivider,
lastUsedProvider,
showPasskey = false,
+ restrictToProviders,
...props
}: SocialLoginButtonsProps): JSX.Element | null {
const { preflight, socialAuthAvailable } = useValues(preflightLogic)
@@ -149,9 +152,15 @@ export function SocialLoginButtons({
const order: string[] = Object.keys(SSO_PROVIDER_NAMES)
const socialProviders = socialAuthAvailable
- ? Object.keys(preflight.available_social_auth_providers).sort((a, b) => order.indexOf(a) - order.indexOf(b))
+ ? Object.keys(preflight.available_social_auth_providers)
+ .filter((provider) => !restrictToProviders || restrictToProviders.includes(provider as SSOProvider))
+ .sort((a, b) => order.indexOf(a) - order.indexOf(b))
: []
+ if (!socialProviders.length && !showPasskey) {
+ return null
+ }
+
return (
<>
{topDivider ? <LemonDivider dashed className="my-4" /> : null}
diff --git a/frontend/src/lib/components/SocialLoginButton/socialLoginUrl.ts b/frontend/src/lib/components/SocialLoginButton/socialLoginUrl.ts
new file mode 100644
index 000000000000..dfbefa80c5d2
--- /dev/null
+++ b/frontend/src/lib/components/SocialLoginButton/socialLoginUrl.ts
@@ -0,0 +1,25 @@
+import { combineUrl, router } from 'kea-router'
+
+import { SSOProvider } from '~/types'
+
+/**
+ * Build the Django login URL for an SSO provider. Lives outside the React components so kea logics
+ * can redirect to a provider without rendering a link.
+ */
+export function getSocialLoginUrl(
+ provider: SSOProvider,
+ extraQueryParams?: Record<string, string>,
+ // Components pass their subscribed `searchParams` so the href stays reactive.
+ searchParams: Record<string, any> = router.values.searchParams
+): string {
+ const loginParams: Record<string, string> = { ...extraQueryParams }
+ const { next } = searchParams
+ if (next) {
+ loginParams.next = next
+ }
+ if (provider === 'saml') {
+ // SAML-based login requires an extra param as technically we can support multiple SAML backends
+ loginParams.idp = 'posthog_custom'
+ }
+ return combineUrl(`/login/${provider}/`, loginParams).url
+}
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.ts
index 76cc544f1ed6..4305de5e40c2 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts
@@ -282,5 +282,215 @@ describe('loginLogic', () => {
await expectLogic(logic).toDispatchActions(['precheckSuccess'])
expect(precheckHandler).toHaveBeenCalledTimes(2)
})
+
+ it('retries a failed precheck instead of caching its fallback for the page session', async () => {
+ precheckHandler.mockImplementationOnce(() => [429, { detail: 'Request was throttled.' }])
+
+ logic.actions.precheck({ email: '[email protected]' })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess'])
+ // The fallback keeps the form usable, but doesn't know about this account's real options.
+ expect(logic.values.precheckResponse).toMatchObject({ status: 'completed', precheckFailed: true })
+ expect(logic.values.precheckResponse.sso_enforcement).toBeUndefined()
+
+ precheckHandler.mockImplementationOnce(() => [
+ 200,
+ { saml_available: false, sso_enforcement: 'google-oauth2' },
+ ])
+ logic.actions.precheck({ email: '[email protected]' })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess'])
+ expect(precheckHandler).toHaveBeenCalledTimes(2)
+ expect(logic.values.precheckResponse.sso_enforcement).toEqual('google-oauth2')
+ })
+ })
+
+ describe('available login methods', () => {
+ let logic: ReturnType<typeof loginLogic.build>
+ let precheckResponse: Record<string, any>
+ const originalVendor = window.navigator.vendor
+
+ beforeEach(() => {
+ setVendor(WEBKIT_VENDOR) // skip the passkey auto-trigger, isolate the precheck response
+ precheckResponse = { saml_available: false }
+ useMocks({ post: { '/api/login/precheck': () => [200, precheckResponse] } })
+ initKeaTests()
+ router.actions.push('/login')
+ logic = loginLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ setVendor(originalVendor)
+ jest.clearAllMocks()
+ })
+
+ async function precheck(response: Record<string, any>): Promise<void> {
+ precheckResponse = response
+ logic.actions.precheck({ email: '[email protected]' })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+ }
+
+ it('keeps password login available before precheck resolves', () => {
+ expect(logic.values.isPasswordLoginUnavailable).toBe(false)
+ expect(logic.values.availableLoginMethods).toEqual([])
+ expect(logic.values.restrictToProviders).toBe(null)
+ })
+
+ it('keeps password login available for a response without the field', async () => {
+ // A server that predates this field must not make the password box disappear.
+ await precheck({ saml_available: false })
+ expect(logic.values.isPasswordLoginUnavailable).toBe(false)
+ expect(logic.values.availableLoginMethods).toEqual(['password'])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
+ expect(logic.values.restrictToProviders).toBe(null)
+ })
+
+ it('keeps password login available for an unknown email', async () => {
+ await precheck({ saml_available: false, password_login_available: true, social_providers: [] })
+ expect(logic.values.isPasswordLoginUnavailable).toBe(false)
+ expect(logic.values.availableLoginMethods).toEqual(['password'])
+ })
+
+ it('offers only the linked provider for a passwordless account', async () => {
+ await precheck({
+ saml_available: false,
+ password_login_available: false,
+ social_providers: ['google-oauth2'],
+ })
+ expect(logic.values.isPasswordLoginUnavailable).toBe(true)
+ expect(logic.values.availableLoginMethods).toEqual(['google-oauth2'])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
+ expect(logic.values.restrictToProviders).toEqual(['google-oauth2'])
+ })
+
+ it('offers only the passkey for a passwordless account with one', async () => {
+ await precheck({
+ saml_available: false,
+ password_login_available: false,
+ social_providers: [],
+ webauthn_credentials: [{ id: 'cred-1', type: 'public-key' }],
+ })
+ expect(logic.values.availableLoginMethods).toEqual(['passkey'])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
+ expect(logic.values.restrictToProviders).toEqual([])
+ })
+
+ it('offers SAML for a passwordless account on a SAML domain', async () => {
+ await precheck({ saml_available: true, password_login_available: false, social_providers: [] })
+ expect(logic.values.availableLoginMethods).toEqual(['saml'])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
+ })
+
+ it('reports a dead end for a passwordless account with nothing else', async () => {
+ await precheck({ saml_available: false, password_login_available: false, social_providers: [] })
+ expect(logic.values.isPasswordLoginUnavailable).toBe(true)
+ expect(logic.values.availableLoginMethods).toEqual([])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(true)
+ })
+
+ it('defers entirely to enforced SSO', async () => {
+ await precheck({
+ saml_available: false,
+ sso_enforcement: 'google-oauth2',
+ password_login_available: false,
+ social_providers: [],
+ })
+ expect(logic.values.availableLoginMethods).toEqual([])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
+ })
+
+ it('falls back to password login when precheck fails, so a 429 cannot lock the form', async () => {
+ useMocks({ post: { '/api/login/precheck': () => [429, { detail: 'Request was throttled.' }] } })
+ logic.actions.precheck({ email: '[email protected]' })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+
+ expect(logic.values.precheckResponse.status).toBe('completed')
+ expect(logic.values.isPasswordLoginUnavailable).toBe(false)
+ expect(logic.values.availableLoginMethods).toEqual(['password'])
+ })
+ })
+
+ describe('auto-redirect to a single login method', () => {
+ let logic: ReturnType<typeof loginLogic.build>
+ let precheckResponse: Record<string, any>
+ let assignMock: jest.Mock
+ const originalVendor = window.navigator.vendor
+
+ beforeEach(() => {
+ setVendor(WEBKIT_VENDOR) // skip the passkey auto-trigger, isolate the redirect
+ precheckResponse = {
+ saml_available: false,
+ password_login_available: false,
+ social_providers: ['google-oauth2'],
+ }
+ useMocks({ post: { '/api/login/precheck': () => [200, precheckResponse] } })
+ initKeaTests()
+ router.actions.push('/login')
+ logic = loginLogic()
+ logic.mount()
+ assignMock = jest.fn()
+ Object.defineProperty(window, 'location', {
+ value: { ...window.location, assign: assignMock },
+ configurable: true,
+ })
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ setVendor(originalVendor)
+ jest.clearAllMocks()
+ })
+
+ it('redirects when the account has exactly one method and the user explicitly submitted the email', async () => {
+ logic.actions.setLoginValue('email', '[email protected]')
+ logic.actions.precheck({ email: '[email protected]', autoAttempt: true })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+
+ expect(logic.values.autoRedirectingToProvider).toBe('google-oauth2')
+ expect(assignMock).toHaveBeenCalledWith('/login/google-oauth2/?email=user%40example.com')
+ })
+
+ it('does not redirect without autoAttempt, so autofill and ?email= links stay put', async () => {
+ logic.actions.setLoginValue('email', '[email protected]')
+ logic.actions.precheck({ email: '[email protected]' })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+
+ expect(logic.values.autoRedirectingToProvider).toBe(null)
+ expect(assignMock).not.toHaveBeenCalled()
+ })
+
+ it('does not redirect when the account has more than one method', async () => {
+ precheckResponse = {
+ saml_available: false,
+ password_login_available: false,
+ social_providers: ['google-oauth2'],
+ webauthn_credentials: [{ id: 'cred-1', type: 'public-key' }],
+ }
+ logic.actions.setLoginValue('email', '[email protected]')
+ logic.actions.precheck({ email: '[email protected]', autoAttempt: true })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+
+ expect(assignMock).not.toHaveBeenCalled()
+ })
+
+ it('does not redirect when the account can use a password', async () => {
+ precheckResponse = { saml_available: false, password_login_available: true, social_providers: [] }
+ logic.actions.setLoginValue('email', '[email protected]')
+ logic.actions.precheck({ email: '[email protected]', autoAttempt: true })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+
+ expect(assignMock).not.toHaveBeenCalled()
+ })
+
+ it('redirects at most once per email', async () => {
+ logic.actions.setLoginValue('email', '[email protected]')
+ logic.actions.precheck({ email: '[email protected]', autoAttempt: true })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+ expect(assignMock).toHaveBeenCalledTimes(1)
+
+ logic.actions.precheck({ email: '[email protected]', autoAttempt: true })
+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()
+ expect(assignMock).toHaveBeenCalledTimes(1)
+ })
})
})
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index dd2d2a11c525..9c08ccef1248 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -9,6 +9,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { ApiError } from 'lib/api-error'
+import { getSocialLoginUrl } from 'lib/components/SocialLoginButton/socialLoginUrl'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isWebKitBrowser } from 'lib/utils/dom'
@@ -18,7 +19,7 @@ import { twoFactorResetLogic } from 'scenes/authentication/two-factor-reset/twoF
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
-import { SSOProvider } from '~/types'
+import { LoginMethod, SSOProvider } from '~/types'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { PreflightStatus } from '../../../types'
@@ -35,8 +36,36 @@ export interface PrecheckResponseType {
saml_available: boolean
status: 'pending' | 'completed'
webauthn_credentials?: PublicKeyCredentialDescriptorJSON[]
+ /**
+ * False only when we know this account exists and has no usable password. Absent (from an older
+ * server or a failed precheck) is treated as true, so the password box never disappears by
+ * accident.
+ */
+ password_login_available?: boolean
+ // The account's linked social identities, already filtered to what this instance supports.
+ social_providers?: SSOProvider[]
// The email this precheck resolved for, used to dedupe redundant prechecks.
email?: string
+ /**
+ * Client-side only: the request failed, so the fields above are permissive defaults rather than
+ * server truth. Such a result is never deduped against — the next precheck for the same email
+ * retries, so a transient 429 can't hide this account's real SSO/SAML/passkey options for the
+ * rest of the page session.
+ */
+ precheckFailed?: boolean
+}
+
+// Precheck result to fall back to when the request fails (e.g. rate limited). Without this the form
+// would stay stuck at `status: 'pending'`, which keeps the password field hidden and swallows submits.
+function precheckFallback(email: string): PrecheckResponseType {
+ return {
+ status: 'completed',
+ saml_available: false,
+ password_login_available: true,
+ social_providers: [],
+ email,
+ precheckFailed: true,
+ }
}
// Routes that should be handled by Django, not the React router
@@ -100,6 +129,9 @@ export interface loginLogicValues {
devUsersLoading: boolean // devLoginLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
preflight: PreflightStatus | null // preflightLogic
+ autoRedirectAttemptedForEmail: string | null
+ autoRedirectingToProvider: SSOProvider | null
+ availableLoginMethods: LoginMethod[]
codeVerification: CodeVerificationForm
codeVerificationAllErrors: Record<string, any>
codeVerificationChanged: boolean
@@ -114,10 +146,12 @@ export interface loginLogicValues {
code: string
detail: string
} | null
+ hasNoConfiguredLoginMethod: boolean
isCodeVerificationSubmitting: boolean
isCodeVerificationValid: boolean
isLoginSubmitting: boolean
isLoginValid: boolean
+ isPasswordLoginUnavailable: boolean
login: LoginForm
loginAllErrors: Record<string, any>
loginChanged: boolean
@@ -134,6 +168,7 @@ export interface loginLogicValues {
success: boolean
} | null
resendResponseLoading: boolean
+ restrictToProviders: SSOProvider[] | null
showCodeVerificationErrors: boolean
showLoginErrors: boolean
signupUrl: string
@@ -152,8 +187,9 @@ export interface loginLogicActions {
exitCodeVerification: () => {
value: true
}
- precheck: ({ email }: { email: string }) => {
+ precheck: ({ email }: { autoAttempt?: boolean; email: string }) => {
email: string
+ autoAttempt?: boolean
}
precheckFailure: (
error: string,
@@ -166,11 +202,13 @@ export interface loginLogicActions {
precheckResponse: PrecheckResponseType,
payload?: {
email: string
+ autoAttempt?: boolean
}
) => {
precheckResponse: PrecheckResponseType
payload?: {
email: string
+ autoAttempt?: boolean
}
}
resendCodeBasedVerification: (_: any) => any
@@ -236,6 +274,13 @@ export interface loginLogicActions {
setLoginValues: (values: DeepPartial<LoginForm>) => {
values: DeepPartial<LoginForm>
}
+ startAutoRedirectToProvider: (
+ provider: SSOProvider,
+ email: string
+ ) => {
+ email: string
+ provider: SSOProvider
+ }
submitCodeVerification: () => {
value: boolean
}
@@ -279,6 +324,17 @@ export interface loginLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface loginLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ isPasswordLoginUnavailable: (precheckResponse: PrecheckResponseType) => boolean
+ availableLoginMethods: (precheckResponse: PrecheckResponseType) => LoginMethod[]
+ hasNoConfiguredLoginMethod: (
+ precheckResponse: PrecheckResponseType,
+ isPasswordLoginUnavailable: boolean,
+ availableLoginMethods: LoginMethod[]
+ ) => boolean
+ restrictToProviders: (
+ precheckResponse: PrecheckResponseType,
+ isPasswordLoginUnavailable: boolean
+ ) => SSOProvider[] | null
signupUrl: (searchParams: Record<string, any>) => string
wasSignedOutForSessionRisk: (searchParams: Record<string, any>) => boolean
}
@@ -304,6 +360,7 @@ export const loginLogic = kea<loginLogicType>([
clearGeneralError: true,
setCodeVerificationRequired: true,
exitCodeVerification: true,
+ startAutoRedirectToProvider: (provider: SSOProvider, email: string) => ({ provider, email }),
}),
reducers({
// This is separate from the login form, so that the form can be submitted even if a general error is present
@@ -324,6 +381,21 @@ export const loginLogic = kea<loginLogicType>([
exitCodeVerification: () => false,
},
],
+ // The provider we're currently bouncing the user to, so the form can say so out loud. The
+ // manual button stays rendered, so a blocked or slow redirect still leaves them a way in.
+ autoRedirectingToProvider: [
+ null as SSOProvider | null,
+ {
+ startAutoRedirectToProvider: (_, { provider }) => provider,
+ },
+ ],
+ // Auto-redirect at most once per email, so a blur → focus → blur cycle can't re-fire it.
+ autoRedirectAttemptedForEmail: [
+ null as string | null,
+ {
+ startAutoRedirectToProvider: (_, { email }) => email,
+ },
+ ],
}),
loaders(({ values }) => ({
precheckResponse: [
@@ -334,6 +406,7 @@ export const loginLogic = kea<loginLogicType>([
email,
}: {
email: string
+ autoAttempt?: boolean
},
breakpoint
) => {
@@ -343,14 +416,24 @@ export const loginLogic = kea<loginLogicType>([
// The autofill effect and the email field's onBlur can both fire for the same
// value — skip the redundant network call (and the duplicate passkey trigger it
- // would cause) when we've already resolved this email.
- if (email === values.precheckResponse.email && values.precheckResponse.status === 'completed') {
+ // would cause) when we've already *successfully* resolved this email. A failed
+ // precheck is never cached, so re-blurring or pressing Enter retries it.
+ if (
+ email === values.precheckResponse.email &&
+ values.precheckResponse.status === 'completed' &&
+ !values.precheckResponse.precheckFailed
+ ) {
return values.precheckResponse
}
breakpoint()
- const response = await api.create<any>('api/login/precheck', { email })
- return { status: 'completed', ...response, email }
+ try {
+ const response = await api.create<any>('api/login/precheck', { email })
+ return { status: 'completed', ...response, email }
+ } catch {
+ // Never let a failed precheck lock the user out of password login.
+ return precheckFallback(email)
+ }
},
},
],
@@ -377,6 +460,57 @@ export const loginLogic = kea<loginLogicType>([
],
})),
selectors(() => ({
+ // True only when we know this account exists and has no usable password, so every variant
+ // hides the password field for the same reason. The explicit `=== false` matters: an older
+ // server or a failed precheck omits the field, and those must keep the password box.
+ // (Variants still decide for themselves whether to hide it while precheck is in flight.)
+ isPasswordLoginUnavailable: [
+ (s) => [s.precheckResponse],
+ (precheckResponse: PrecheckResponseType): boolean => precheckResponse.password_login_available === false,
+ ],
+ // Every way this specific account can get in. Empty until precheck resolves, and empty when
+ // SSO is enforced (that path takes over the whole form).
+ availableLoginMethods: [
+ (s) => [s.precheckResponse],
+ (precheckResponse: PrecheckResponseType): LoginMethod[] => {
+ if (precheckResponse.status !== 'completed' || precheckResponse.sso_enforcement) {
+ return []
+ }
+ const methods: LoginMethod[] = []
+ if (precheckResponse.password_login_available !== false) {
+ methods.push('password')
+ }
+ for (const provider of precheckResponse.social_providers ?? []) {
+ methods.push(provider)
+ }
+ if (precheckResponse.saml_available && !methods.includes('saml')) {
+ methods.push('saml')
+ }
+ if (precheckResponse.webauthn_credentials?.length) {
+ methods.push('passkey')
+ }
+ return methods
+ },
+ ],
+ // A passwordless account with nothing else linked. They can only get back in via a reset.
+ hasNoConfiguredLoginMethod: [
+ (s) => [s.precheckResponse, s.isPasswordLoginUnavailable, s.availableLoginMethods],
+ (
+ precheckResponse: PrecheckResponseType,
+ isPasswordLoginUnavailable: boolean,
+ availableLoginMethods: LoginMethod[]
+ ): boolean =>
+ // `availableLoginMethods` is deliberately empty when SSO is enforced — that path owns
+ // the whole form, so it isn't a dead end.
+ !precheckResponse.sso_enforcement && isPasswordLoginUnavailable && availableLoginMethods.length === 0,
+ ],
+ // Allowlist for the social button row: only narrow it once we know the account is passwordless
+ // and which providers it has. `null` means "show everything the instance offers", as before.
+ restrictToProviders: [
+ (s) => [s.precheckResponse, s.isPasswordLoginUnavailable],
+ (precheckResponse: PrecheckResponseType, isPasswordLoginUnavailable: boolean): SSOProvider[] | null =>
+ isPasswordLoginUnavailable ? (precheckResponse.social_providers ?? []) : null,
+ ],
signupUrl: [
() => [router.selectors.searchParams],
(searchParams: Record<string, string>) => {
@@ -483,7 +617,7 @@ export const loginLogic = kea<loginLogicType>([
exitCodeVerification: () => {
actions.resetCodeVerification()
},
- precheckSuccess: async (_, breakpoint) => {
+ precheckSuccess: async ({ payload }, breakpoint) => {
const { precheckResponse } = values
// Auto-trigger the modal passkey prompt if the user has passkeys and SSO isn't enforced.
// Skip on WebKit, it freezes Safari when triggered without a user gesture.
@@ -498,6 +632,28 @@ export const loginLogic = kea<loginLogicType>([
const { passkeyLogic } = await import('scenes/authentication/shared/passkeyLogic')
breakpoint()
passkeyLogic.actions.beginPasskeyLogin(precheckResponse.webauthn_credentials)
+ return
+ }
+
+ // A passwordless account with exactly one way in: send them straight to it, the same way
+ // an SSO-enforced domain does. Only ever on an explicit blur/Enter (`autoAttempt`), never
+ // on autofill or a `?email=` deep link, so a mistyped address can't bounce the user out
+ // of the form.
+ const { email } = values.login
+ const [onlyMethod] = values.availableLoginMethods
+ if (
+ payload?.autoAttempt &&
+ values.isPasswordLoginUnavailable &&
+ values.availableLoginMethods.length === 1 &&
+ onlyMethod !== 'passkey' &&
+ onlyMethod !== 'password' &&
+ onlyMethod !== null &&
+ values.autoRedirectAttemptedForEmail !== email
+ ) {
+ breakpoint()
+ actions.startAutoRedirectToProvider(onlyMethod, email)
+ // `assign` rather than `replace` so the browser Back button returns to /login.
+ window.location.assign(getSocialLoginUrl(onlyMethod, { email }))
}
},
})),
diff --git a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
index 49cbcc1eb819..0a16531ebb3a 100644
--- a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
+++ b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
@@ -11,6 +11,7 @@ import { getCookie } from 'lib/api'
import { BridgePage } from 'lib/components/BridgePage/BridgePage'
import { SSOEnforcedLoginButton, SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'
import { supportLogic } from 'lib/components/Support/supportLogic'
+import { SSO_PROVIDER_NAMES } from 'lib/constants'
import { usePrevious } from 'lib/hooks/usePrevious'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -50,6 +51,10 @@ function Login(): JSX.Element {
devUsers,
devUsersLoading,
devLoginTimeSavedLabel,
+ isPasswordLoginUnavailable,
+ hasNoConfiguredLoginMethod,
+ restrictToProviders,
+ autoRedirectingToProvider,
} = useValues(loginLogic)
const { preflight } = useValues(preflightLogic)
const allowDevLogin = !!preflight?.allow_dev_login
@@ -62,7 +67,8 @@ function Login(): JSX.Element {
const passwordInputRef = useRef<HTMLInputElement>(null)
const preventPasswordError = useRef(false)
- const isPasswordHidden = precheckResponse.status === 'pending' || precheckResponse.sso_enforcement
+ const isPasswordHidden =
+ precheckResponse.status === 'pending' || !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable
const isCodeSent = codeVerificationRequired
const loginTitle = isCodeSent ? 'Enter your login code' : 'Log in'
const wasPasswordHiddenRef = useRef(isPasswordHidden)
@@ -77,9 +83,11 @@ function Login(): JSX.Element {
if (!isPasswordHidden) {
passwordInputRef.current?.focus()
} else if (!wasPasswordHidden) {
- // clear form when transitioning from visible to hidden
- resetLogin()
+ // Drop any typed password when the field goes away, but keep the email — the SSO and
+ // social buttons we show instead need it.
+ resetLogin({ email: login.email, password: '' })
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPasswordHidden, resetLogin])
// Trigger precheck for password manager autofill/paste (detected by large character delta)
@@ -200,10 +208,14 @@ function Login(): JSX.Element {
// The `webauthn` token enables passkey autofill (conditional UI), which
// we only offer on WebKit; elsewhere the auto-modal handles passkeys.
autoComplete={isWebKitBrowser() ? 'username webauthn' : undefined}
- onBlur={() => precheck({ email: login.email })}
+ // `autoAttempt` is only ever set here and on Enter — an explicit
+ // gesture — so autofill or a mistyped address can't bounce the user
+ // out to an identity provider.
+ onBlur={() => precheck({ email: login.email, autoAttempt: true })}
onPressEnter={(e) => {
if (isPasswordHidden) {
e.preventDefault() // Don't trigger submission if password field is still hidden
+ precheck({ email: login.email, autoAttempt: true })
passwordInputRef.current?.focus()
}
}}
@@ -237,8 +249,26 @@ function Login(): JSX.Element {
</LemonField>
</div>
- {/* Show regular login button if SSO is not enforced */}
- {!precheckResponse.sso_enforcement && (
+ {hasNoConfiguredLoginMethod && (
+ <LemonBanner type="warning">
+ No sign-in method is set up for this account. Use{' '}
+ <Link to={[urls.passwordReset(), { email: login.email }]} data-attr="forgot-password">
+ Forgot your password?
+ </Link>{' '}
+ to set a password by email.
+ </LemonBanner>
+ )}
+
+ {autoRedirectingToProvider && (
+ <p className="text-secondary text-center mb-0">
+ Redirecting to {SSO_PROVIDER_NAMES[autoRedirectingToProvider]}…
+ </p>
+ )}
+
+ {/* Show regular login button unless SSO is enforced or we know the account has
+ no password to submit — otherwise it's a button that does nothing. It stays
+ while precheck is pending, where it doubles as a "continue" affordance. */}
+ {!precheckResponse.sso_enforcement && !isPasswordLoginUnavailable && (
<LemonButton
type="primary"
status="alt"
@@ -286,14 +316,21 @@ function Login(): JSX.Element {
</Link>
</div>
)}
- {!isCodeSent && !precheckResponse.saml_available && !precheckResponse.sso_enforcement && (
- <SocialLoginButtons
- caption="Or log in with"
- topDivider
- lastUsedProvider={lastLoginMethod}
- showPasskey
- />
- )}
+ {/* Normally SAML replaces this row, but when the account has no password we need to
+ show whatever it does have. */}
+ {!isCodeSent &&
+ !precheckResponse.sso_enforcement &&
+ (!precheckResponse.saml_available || isPasswordLoginUnavailable) && (
+ <SocialLoginButtons
+ caption={isPasswordLoginUnavailable ? 'Log in with' : 'Or log in with'}
+ topDivider
+ lastUsedProvider={lastLoginMethod}
+ restrictToProviders={restrictToProviders}
+ // Once we know the account's methods, only offer a passkey if it actually has
+ // one — otherwise this is the same dead button we're removing.
+ showPasskey={!isPasswordLoginUnavailable || !!precheckResponse.webauthn_credentials?.length}
+ />
+ )}
{allowDevLogin && (
<div className="deprecated-space-y-2 border-t border-dashed pt-4 mt-4">
<div className="flex items-center justify-between">
diff --git a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx
index 4f3a4cebcff3..55f018b32f8d 100644
--- a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx
+++ b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx
@@ -8,6 +8,7 @@ import { IconCheckCircle } from '@posthog/icons'
import { getCookie } from 'lib/api'
import { SocialLoginButtons, SSOEnforcedLoginButton } from 'lib/components/SocialLoginButton/SocialLoginButton'
import { supportLogic } from 'lib/components/Support/supportLogic'
+import { SSO_PROVIDER_NAMES } from 'lib/constants'
import { usePrevious } from 'lib/hooks/usePrevious'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -45,10 +46,14 @@ function Login(): JSX.Element {
resendResponse,
codeVerificationRequired,
isCodeVerificationSubmitting,
+ isPasswordLoginUnavailable,
+ hasNoConfiguredLoginMethod,
+ restrictToProviders,
+ autoRedirectingToProvider,
} = useValues(loginLogic)
const { preflight } = useValues(preflightLogic)
- const isPasswordHidden = !!precheckResponse.sso_enforcement
+ const isPasswordHidden = !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable
const isCodeSent = codeVerificationRequired
const lastLoginMethod = getCookie(LAST_LOGIN_METHOD_COOKIE) as LoginMethod
const prevEmail = usePrevious(login.email)
@@ -190,7 +195,10 @@ function Login(): JSX.Element {
autoComplete={isWebKitBrowser() ? 'username webauthn' : 'email'}
value={value ?? ''}
onChange={onChange}
- onBlur={() => precheck({ email: login.email })}
+ // `autoAttempt` is only ever set on this explicit gesture, so
+ // autofill or a mistyped address can't bounce the user out to an
+ // identity provider.
+ onBlur={() => precheck({ email: login.email, autoAttempt: true })}
status={error ? 'danger' : 'default'}
fullWidth
/>
@@ -229,7 +237,26 @@ function Login(): JSX.Element {
)}
</LemonField>
)}
- {!precheckResponse.sso_enforcement && (
+ {hasNoConfiguredLoginMethod && (
+ <div className="py-2.5 px-3 text-sm leading-normal text-primary text-left bg-warning-highlight border border-warning rounded">
+ No sign-in method is set up for this account. Use{' '}
+ <Link
+ to={[urls.passwordReset(), { email: login.email }]}
+ data-attr="forgot-password"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Forgot password?
+ </Link>{' '}
+ to set a password by email.
+ </div>
+ )}
+ {autoRedirectingToProvider && (
+ <p className="text-sm text-secondary text-center mb-0">
+ Redirecting to {SSO_PROVIDER_NAMES[autoRedirectingToProvider]}…
+ </p>
+ )}
+ {/* No password to submit means this button would do nothing */}
+ {!precheckResponse.sso_enforcement && !isPasswordLoginUnavailable && (
<LemonButton
type="primary"
size="large"
@@ -258,15 +285,22 @@ function Login(): JSX.Element {
)}
</Form>
)}
- {!isCodeSent && !precheckResponse.saml_available && !precheckResponse.sso_enforcement && (
- <SocialLoginButtons
- topDivider
- caption="Or log in with"
- captionLocation="top"
- lastUsedProvider={lastLoginMethod}
- showPasskey
- />
- )}
+ {/* Normally SAML replaces this row, but when the account has no password we need to
+ show whatever it does have. */}
+ {!isCodeSent &&
+ !precheckResponse.sso_enforcement &&
+ (!precheckResponse.saml_available || isPasswordLoginUnavailable) && (
+ <SocialLoginButtons
+ topDivider
+ caption={isPasswordLoginUnavailable ? 'Log in with' : 'Or log in with'}
+ captionLocation="top"
+ lastUsedProvider={lastLoginMethod}
+ restrictToProviders={restrictToProviders}
+ // Once we know the account's methods, only offer a passkey if it actually has
+ // one — otherwise this is the same dead button we're removing.
+ showPasskey={!isPasswordLoginUnavailable || !!precheckResponse.webauthn_credentials?.length}
+ />
+ )}
</PaperDeskCard>
</PaperDeskScene>
)
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index b4d9d5a5ce5d..22553b850eaf 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -55,6 +55,7 @@ from posthog.event_usage import report_user_logged_in, report_user_password_rese
from posthog.exceptions_capture import capture_exception
from posthog.geoip import get_geoip_properties
from posthog.helpers.dev_login import is_dev_login_allowed
+from posthog.helpers.email_utils import EmailLookupHandler
from posthog.helpers.two_factor_session import (
CODE_MAX_ATTEMPTS,
LOGIN_CODE_VERIFICATION_COUNTER,
@@ -72,6 +73,7 @@ from posthog.passkey import generate_passkey_authentication_options, verify_pass
from posthog.rate_limit import (
CodeBasedVerificationResendThrottle,
CodeBasedVerificationThrottle,
+ LoginPrecheckThrottle,
TwoFactorThrottle,
UserPasswordResetThrottle,
)
@@ -399,8 +401,8 @@ class LoginPrecheckSerializer(serializers.Serializer):
email = serializers.EmailField()
def to_representation(
- self, instance: dict[str, str | list[WebauthnCredentialPrecheck]]
- ) -> dict[str, str | list[WebauthnCredentialPrecheck]]:
+ self, instance: dict[str, str | bool | list[str] | list[WebauthnCredentialPrecheck]]
+ ) -> dict[str, str | bool | list[str] | list[WebauthnCredentialPrecheck]]:
return instance
def create(self, validated_data: dict[str, str]) -> Any:
@@ -421,10 +423,48 @@ class LoginPrecheckSerializer(serializers.Serializer):
for cred in credentials
]
+ saml_available = OrganizationDomain.objects.get_is_saml_available_for_email(email)
+
return {
"sso_enforcement": OrganizationDomain.objects.get_sso_enforcement_for_email_address(email),
- "saml_available": OrganizationDomain.objects.get_is_saml_available_for_email(email),
+ "saml_available": saml_available,
"webauthn_credentials": webauthn_credentials,
+ **self._available_local_methods(email, saml_available=saml_available),
+ }
+
+ @staticmethod
+ def _available_local_methods(email: str, *, saml_available: bool) -> dict[str, Any]:
+ """
+ Report whether this account can log in with a password, and which of its linked social
+ identities are actually usable on this instance, so the login form can stop offering a
+ password box (or a dead SSO button) to an account that cannot use it.
+
+ An email with no active user looks identical to a user who does have a password — a typo
+ must never be a dead end, and it keeps the account-existence signal limited to accounts
+ that are genuinely passwordless.
+ """
+ # Same lookup login itself uses (`UserManager.get_by_natural_key`), so precheck can never
+ # describe a different account than the one a password would authenticate: exact case first,
+ # then case-insensitive, and deterministic (last logged in) if case variations coexist.
+ user = EmailLookupHandler.get_user_by_email(email)
+ if user is None:
+ return {"password_login_available": True, "social_providers": []}
+
+ # Mirrors `UserSerializer.get_has_password`: `has_usable_password()` is True for an empty
+ # password, so the `bool(...)` half of the check is load-bearing.
+ password_login_available = bool(user.password) and user.has_usable_password()
+
+ usable_providers = {
+ provider for provider, available in get_instance_available_sso_providers().items() if available
+ }
+ if saml_available:
+ # SAML is domain-configured rather than instance-configured, so it isn't covered above.
+ usable_providers.add("saml")
+ linked_providers = set(user.social_auth.values_list("provider", flat=True))
+
+ return {
+ "password_login_available": password_login_available,
+ "social_providers": sorted(linked_providers & usable_providers),
}
@@ -1076,6 +1116,7 @@ class LoginPrecheckViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
queryset = User.objects.none()
serializer_class = LoginPrecheckSerializer
permission_classes = (permissions.AllowAny,)
+ throttle_classes = [] if settings.E2E_TESTING else [LoginPrecheckThrottle]
class PasswordResetSerializer(serializers.Serializer):
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 57a82f0b9c96..d98dd14adec9 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -88,7 +88,14 @@ class TestLoginPrecheckAPI(APIBaseTest):
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": None, "saml_available": False, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
def test_login_precheck_with_sso_enforced_with_invalid_license(self):
@@ -104,7 +111,14 @@ class TestLoginPrecheckAPI(APIBaseTest):
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
- response.json(), {"sso_enforcement": None, "saml_available": False, "webauthn_credentials": []}
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
)
def test_login_precheck_returns_webauthn_credentials_for_user_with_verified_passkey(self):
@@ -191,6 +205,134 @@ class TestLoginPrecheckAPI(APIBaseTest):
self.assertEqual(len(response_data["webauthn_credentials"]), 2)
+ def test_login_precheck_reports_password_login_available_for_user_with_password(self):
+ User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], True)
+
+ def test_login_precheck_reports_password_login_unavailable_for_passwordless_user(self):
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": False,
+ "social_providers": [],
+ },
+ )
+
+ def test_login_precheck_reports_password_login_unavailable_for_blank_password(self):
+ # `has_usable_password()` is True for an empty password, so this exercises the `bool(...)` half
+ # of the check — a blank password is not something anyone can log in with.
+ user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ User.objects.filter(pk=user.pk).update(password="")
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], False)
+
+ def test_login_precheck_returns_linked_social_provider_configured_on_instance(self):
+ user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserSocialAuth.objects.create(user=user, provider="github", uid="12345")
+
+ with self.settings(SOCIAL_AUTH_GITHUB_KEY="key", SOCIAL_AUTH_GITHUB_SECRET="secret"):
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], False)
+ self.assertEqual(response.json()["social_providers"], ["github"])
+
+ def test_login_precheck_omits_linked_social_provider_not_configured_on_instance(self):
+ # Offering this provider would render a button that can't work.
+ user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserSocialAuth.objects.create(user=user, provider="github", uid="12345")
+
+ with self.settings(SOCIAL_AUTH_GITHUB_KEY=None, SOCIAL_AUTH_GITHUB_SECRET=None):
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["social_providers"], [])
+
+ def test_login_precheck_treats_unknown_email_as_password_login_available(self):
+ # An unknown email must be indistinguishable from a user who has a password, so a typo is
+ # never a dead end and we don't leak which addresses have accounts.
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], True)
+ self.assertEqual(response.json()["social_providers"], [])
+
+ def test_login_precheck_treats_inactive_passwordless_user_as_unknown(self):
+ user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ user.is_active = False
+ user.save()
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], True)
+
+ def test_login_precheck_is_rate_limited_by_ip(self):
+ cache.clear()
+ # Don't leave 30 throttle entries behind for whatever test runs next.
+ self.addCleanup(cache.clear)
+ with self.settings(E2E_TESTING=False):
+ for i in range(30):
+ response = self.client.post("/api/login/precheck", {"email": f"enumerate-{i}@posthog.com"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK, f"request {i} was throttled early")
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_login_precheck_is_not_rate_limited_for_the_callers_own_email(self):
+ # The time-sensitive re-auth modal prechecks the logged-in user's own email on a timer, and it
+ # tells them nothing they don't already have.
+ cache.clear()
+ self.addCleanup(cache.clear)
+ self.client.force_login(self.user)
+
+ with self.settings(E2E_TESTING=False):
+ for i in range(35):
+ response = self.client.post("/api/login/precheck", {"email": self.user.email.upper()})
+ self.assertEqual(response.status_code, status.HTTP_200_OK, f"request {i} was throttled")
+
+ def test_login_precheck_is_rate_limited_for_an_authenticated_caller_probing_other_emails(self):
+ # Being signed in with any account must not buy unlimited enumeration of other people's
+ # sign-in methods — the endpoint is `AllowAny` and has no ownership check.
+ cache.clear()
+ self.addCleanup(cache.clear)
+ self.client.force_login(self.user)
+
+ with self.settings(E2E_TESTING=False):
+ for i in range(30):
+ response = self.client.post("/api/login/precheck", {"email": f"victim-{i}@posthog.com"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK, f"request {i} was throttled early")
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_login_precheck_prefers_the_exact_case_match_like_login_does(self):
+ # `User.email` is only unique case-*sensitively*, so variations can coexist. Precheck must
+ # describe the same account login would authenticate — an exact-case match wins.
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ with_password = User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
+ # `create_user` normalizes the address to lowercase, so write the variation in directly — the
+ # accounts this guards against predate that normalization.
+ User.objects.filter(pk=with_password.pk).update(email="[email protected]")
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], True)
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["password_login_available"], False)
+
class TestLoginAPI(APIBaseTest):
"""
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 56d9c767300a..f653b5aca602 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -355,6 +355,29 @@ class SignupEmailPrecheckThrottle(IPThrottle):
rate = "30/minute"
+class LoginPrecheckThrottle(IPThrottle):
+ """
+ Rate limit login precheck requests by IP.
+
+ The response reveals which sign-in methods a passwordless account has, so cap it per-IP to make
+ bulk enumeration expensive. Per-email throttling would be useless here — enumeration uses a
+ different email on every request.
+ """
+
+ scope = "login_precheck"
+ rate = "30/minute"
+
+ def allow_request(self, request, view):
+ # The time-sensitive re-auth modal prechecks the logged-in user's *own* email, and that tells
+ # them nothing they don't already have — so exempt exactly that. The endpoint is `AllowAny`
+ # with no ownership check, so a broader exemption would let anyone with a throwaway account
+ # enumerate other people's sign-in methods for free.
+ email = request.data.get("email", "") if isinstance(request.data, dict) else ""
+ if request.user.is_authenticated and email and email.casefold() == (request.user.email or "").casefold():
+ return True
+ return super().allow_request(request, view)
+
+
class SignupResendInviteThrottle(UserOrEmailRateThrottle):
"""
Rate limit signup invite-resend requests per email address.