diff --git a/.changeset/tidy-emails-sign-in.md b/.changeset/tidy-emails-sign-in.md new file mode 100644 index 00000000000..a0dafd7707d --- /dev/null +++ b/.changeset/tidy-emails-sign-in.md @@ -0,0 +1,5 @@ +--- +'@clerk/ui': patch +--- + +Allow password sign-in on instances with Enterprise SSO enabled when an unverified email or phone has been locked by code attempts. Reveal the password field after identifier lockout so users can enter their password manually. diff --git a/packages/backend/src/api/endpoints/UserApi.ts b/packages/backend/src/api/endpoints/UserApi.ts index 28f2b134078..03fd53f44cb 100644 --- a/packages/backend/src/api/endpoints/UserApi.ts +++ b/packages/backend/src/api/endpoints/UserApi.ts @@ -20,9 +20,9 @@ const basePath = '/users'; /** @generateWithEmptyComment */ export type UserCountParams = { - /** Counts users with emails that match the given query, via case-insensitive partial match. For example, `emailAddress=hello` will match a user with the email `HELLO@example.com`. Accepts up to 100 email addresses. */ + /** Counts users with the specified email addresses. When an address has a verified owner, unverified copies on other accounts are excluded. Accepts up to 100 email addresses. */ emailAddress?: string[]; - /** Counts users with phone numbers that match the given query, via case-insensitive partial match. For example, `phoneNumber=555` will match a user with the phone number `+1555xxxxxxx`. Accepts up to 100 phone numbers. */ + /** Counts users with the specified phone numbers. When a number has a verified owner, unverified copies on other accounts are excluded. Accepts up to 100 phone numbers. */ phoneNumber?: string[]; /** Counts users with usernames that match the given query, via case-insensitive partial match. For example, `username=CoolUser` will match a user with the username `SomeCoolUser`. Accepts up to 100 usernames. */ username?: string[]; @@ -38,9 +38,9 @@ export type UserCountParams = { /** @generateWithEmptyComment */ export type UserListParams = ClerkPaginationRequest<{ - /** Filters users with the specified email addresses. Accepts up to 100 email addresses. */ + /** Filters users with the specified email addresses. When an address has a verified owner, unverified copies on other accounts are excluded. Accepts up to 100 email addresses. */ emailAddress?: string[]; - /** Filters users with the specified phone numbers. Accepts up to 100 phone numbers. */ + /** Filters users with the specified phone numbers. When a number has a verified owner, unverified copies on other accounts are excluded. Accepts up to 100 phone numbers. */ phoneNumber?: string[]; /** Filters users with the specified usernames. Accepts up to 100 usernames. */ username?: string[]; @@ -233,13 +233,13 @@ export type UserPasswordHashingParams = { export type CreateUserParams = { /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */ externalId?: string; - /** The email addresses to assign to the user. Each address must be unique across your instance. The first email address becomes the user's primary email address. Addresses are created as verified by default; use `emailAddressIdentificationStatus` to create reserved addresses. */ + /** The email addresses to assign to the user. Each address must be unique across your instance when creating the user. A reserved address can later coexist with a verified copy on a separate account after its owner proves possession. The first email address becomes the user's primary email address. Addresses are created as verified by default; use `emailAddressIdentificationStatus` to create reserved addresses. */ emailAddress?: string[]; - /** Sets the creation status of each email address. Entries correspond by index to `emailAddress`, and the array must contain exactly one entry per email address. If omitted, every email address is created as `'verified'`. Use `'reserved'` to create an unverified address that can still be used for sign-in and cannot be claimed by another user. */ + /** Sets the creation status of each email address. Entries correspond by index to `emailAddress`, and the array must contain exactly one entry per email address. If omitted, every email address is created as `'verified'`. Use `'reserved'` to create an unverified address that can identify this user for password sign-in when no verified owner exists. It cannot authenticate this user through email verification; a verified owner can claim it on a separate account, where the verified copy coexists with this user's reserved copy. */ emailAddressIdentificationStatus?: ('verified' | 'reserved')[]; - /** The phone numbers to assign to the user. Each number must be unique across your instance. The first phone number becomes the user's primary phone number. Numbers are created as verified by default; use `phoneNumberIdentificationStatus` to create reserved numbers. */ + /** The phone numbers to assign to the user. Each number must be unique across your instance when creating the user. A reserved number can later coexist with a verified copy on a separate account after its owner proves possession. The first phone number becomes the user's primary phone number. Numbers are created as verified by default; use `phoneNumberIdentificationStatus` to create reserved numbers. */ phoneNumber?: string[]; - /** Sets the creation status of each phone number. Entries correspond by index to `phoneNumber`, and the array must contain exactly one entry per phone number. If omitted, every phone number is created as `'verified'`. Use `'reserved'` to create an unverified number that can still be used for sign-in and cannot be claimed by another user. */ + /** Sets the creation status of each phone number. Entries correspond by index to `phoneNumber`, and the array must contain exactly one entry per phone number. If omitted, every phone number is created as `'verified'`. Use `'reserved'` to create an unverified number that can identify this user for password sign-in when no verified owner exists. It cannot authenticate this user through phone verification; a verified owner can claim it on a separate account, where the verified copy coexists with this user's reserved copy. */ phoneNumberIdentificationStatus?: ('verified' | 'reserved')[]; /** The username to assign to the user. Must be unique across your instance. */ username?: string; @@ -467,7 +467,7 @@ export class UserAPI extends AbstractAPI { * * Your settings in the [Clerk Dashboard](https://dashboard.clerk.com) determine how you should setup your user model. Anything **Required** will need to be provided when creating a user. Trying to add a field that isn't enabled will result in an error. * - * By default, email addresses and phone numbers created using this method are verified automatically. Use `emailAddressIdentificationStatus` and `phoneNumberIdentificationStatus` to create any of them as reserved. Reserved identifiers are unverified, but they can still be used for sign-in and cannot be claimed by another user. + * By default, email addresses and phone numbers created using this method are verified automatically. Use `emailAddressIdentificationStatus` and `phoneNumberIdentificationStatus` to create any of them as reserved. Reserved identifiers are unverified. They can identify this user for password sign-in only when no verified owner exists, but email or phone verification cannot authenticate this user. A verified owner can claim the contact on a separate account, where the verified copy coexists with this user's reserved copy. * * > [!CAUTION] * > diff --git a/packages/ui/src/components/SignIn/SignInStart.tsx b/packages/ui/src/components/SignIn/SignInStart.tsx index 71b14ab903b..de1d326cdbd 100644 --- a/packages/ui/src/components/SignIn/SignInStart.tsx +++ b/packages/ui/src/components/SignIn/SignInStart.tsx @@ -1,4 +1,5 @@ import { getAlternativePhoneCodeProviderData } from '@clerk/shared/alternativePhoneCode'; +import { isUserLockedError } from '@clerk/shared/error'; import { inertProps } from '@clerk/shared/inert'; import { ERROR_CODES, SIGN_UP_MODES } from '@clerk/shared/internal/clerk-js/constants'; import { clerkInvalidFAPIResponse } from '@clerk/shared/internal/clerk-js/errors'; @@ -140,6 +141,7 @@ function SignInStartInternal(): JSX.Element { label: localizationKeys('formFieldLabel__password'), placeholder: localizationKeys('formFieldInputPlaceholder__password') as any, }); + const [showInstantPasswordField, setShowInstantPasswordField] = useState(false); const [alternativePhoneCodeProvider, setAlternativePhoneCodeProvider] = useState(null); @@ -351,19 +353,42 @@ function SignInStartInternal(): JSX.Element { signInCreatePromise: Promise, fields: Array>, ) => { - return signInCreatePromise.then(signInResource => { - if (!userSettings.enterpriseSSO.enabled) { - return signInResource; - } - /** - * For instances with Enterprise SSO enabled, perform sign in with password only when it is allowed for the identified user. - */ - const passwordField = fields.find(f => f.name === 'password')?.value; - if (!passwordField || signInResource.supportedFirstFactors?.some(ff => ff.strategy === 'enterprise_sso')) { - return signInResource; - } - return signInResource.attemptFirstFactor({ strategy: 'password', password: passwordField }); - }); + return signInCreatePromise.then( + signInResource => { + if (!userSettings.enterpriseSSO.enabled) { + return signInResource; + } + /** + * For instances with Enterprise SSO enabled, perform sign in with password only when it is allowed for the identified user. + */ + const passwordField = fields.find(f => f.name === 'password')?.value; + if (!passwordField || signInResource.supportedFirstFactors?.some(ff => ff.strategy === 'enterprise_sso')) { + return signInResource; + } + return signInResource.attemptFirstFactor({ strategy: 'password', password: passwordField }); + }, + error => { + const passwordField = fields.find(f => f.name === 'password')?.value; + if (!userSettings.enterpriseSSO.enabled || !isUserLockedError(error)) { + throw error; + } + if (!passwordField) { + setShowInstantPasswordField(true); + throw error; + } + return signIn + .create({ + identifier: buildRequest(fields).identifier, + password: passwordField, + strategy: 'password', + }) + .catch(fallbackError => { + setShowInstantPasswordField(true); + handleError(fallbackError, [identifierField, instantPasswordField], card.setError); + throw new Error('password_fallback_failed'); + }); + }, + ); }; const signInWithFields = async ( @@ -679,6 +704,7 @@ function SignInStartInternal(): JSX.Element { @@ -740,14 +766,16 @@ function SignInStartInternal(): JSX.Element { const InstantPasswordRow = ({ field, + forceVisible = false, onForgotPasswordClick, }: { field?: FormControlState<'password'>; + forceVisible?: boolean; onForgotPasswordClick?: React.MouseEventHandler; }) => { const [autofilled, setAutofilled] = useState(false); const ref = useRef(null); - const show = !!(autofilled || field?.value); + const show = !!(forceVisible || autofilled || field?.value); // show password if it's autofilled by the browser useLayoutEffect(() => { diff --git a/packages/ui/src/components/SignIn/__tests__/SignInStart.test.tsx b/packages/ui/src/components/SignIn/__tests__/SignInStart.test.tsx index 1da263fbd58..522dbd5d1e4 100644 --- a/packages/ui/src/components/SignIn/__tests__/SignInStart.test.tsx +++ b/packages/ui/src/components/SignIn/__tests__/SignInStart.test.tsx @@ -472,6 +472,273 @@ describe('SignInStart', () => { }); describe('Enterprise SSO', () => { + it('submits an autofilled password only after identifier creation allows password sign-in', async () => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + f.withEnterpriseSso(); + }); + fixtures.signIn.create.mockResolvedValueOnce({ + status: 'needs_first_factor', + supportedFirstFactors: [{ strategy: 'password' }], + attemptFirstFactor: fixtures.signIn.attemptFirstFactor, + } as unknown as SignInResource); + fixtures.signIn.attemptFirstFactor.mockResolvedValueOnce({ + status: 'complete', + createdSessionId: 'sess_password', + } as SignInResource); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + fireEvent.change(container.querySelector('#password-field') as Element, { + target: { value: 'some-password' }, + }); + fireEvent.submit(container.querySelector('form') as Element); + + await waitFor(() => { + expect(fixtures.clerk.setActive).toHaveBeenCalledWith({ + session: 'sess_password', + navigate: expect.any(Function), + }); + }); + expect(fixtures.signIn.create).toHaveBeenCalledExactlyOnceWith({ identifier: 'hello@clerk.com' }); + expect(fixtures.signIn.attemptFirstFactor).toHaveBeenCalledExactlyOnceWith({ + strategy: 'password', + password: 'some-password', + }); + }); + + it('does not retry when the password attempt itself is locked', async () => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + f.withEnterpriseSso(); + }); + fixtures.signIn.create.mockResolvedValueOnce({ + status: 'needs_first_factor', + supportedFirstFactors: [{ strategy: 'password' }], + attemptFirstFactor: fixtures.signIn.attemptFirstFactor, + } as unknown as SignInResource); + fixtures.signIn.attemptFirstFactor.mockRejectedValueOnce( + new ClerkAPIResponseError('Locked', { + data: [{ code: 'user_locked', message: 'Locked', long_message: 'Locked' }], + status: 403, + }), + ); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + fireEvent.change(container.querySelector('#password-field') as Element, { + target: { value: 'some-password' }, + }); + fireEvent.submit(container.querySelector('form') as Element); + + await screen.findByText('Locked'); + expect(fixtures.signIn.create).toHaveBeenCalledTimes(1); + expect(fixtures.signIn.attemptFirstFactor).toHaveBeenCalledExactlyOnceWith({ + strategy: 'password', + password: 'some-password', + }); + expect(fixtures.clerk.setActive).not.toHaveBeenCalled(); + }); + + it('retries a locked identifier with the supplied password and activates the authenticated session', async () => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + f.withEnterpriseSso(); + }); + fixtures.signIn.create + .mockRejectedValueOnce( + new ClerkAPIResponseError('Locked', { + data: [{ code: 'user_locked', message: 'Locked', long_message: 'Locked' }], + status: 403, + }), + ) + .mockResolvedValueOnce({ status: 'complete', createdSessionId: 'sess_password' } as SignInResource); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + fireEvent.change(container.querySelector('#password-field') as Element, { + target: { value: 'some-password' }, + }); + fireEvent.submit(container.querySelector('form') as Element); + + await waitFor(() => { + expect(fixtures.clerk.setActive).toHaveBeenCalledWith({ + session: 'sess_password', + navigate: expect.any(Function), + }); + }); + expect(fixtures.signIn.create).toHaveBeenCalledTimes(2); + expect(fixtures.signIn.create).toHaveBeenNthCalledWith(1, { identifier: 'hello@clerk.com' }); + expect(fixtures.signIn.create).toHaveBeenNthCalledWith(2, { + identifier: 'hello@clerk.com', + password: 'some-password', + strategy: 'password', + }); + expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled(); + }); + + it('reveals the password field after identifier lockout so the owner can retry manually', async () => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + f.withEnterpriseSso(); + }); + const lockedError = new ClerkAPIResponseError('Locked', { + data: [{ code: 'user_locked', message: 'Locked', long_message: 'Locked' }], + status: 403, + }); + fixtures.signIn.create + .mockRejectedValueOnce(lockedError) + .mockRejectedValueOnce(lockedError) + .mockResolvedValueOnce({ status: 'complete', createdSessionId: 'sess_password' } as SignInResource); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + await userEvent.click(screen.getByText('Continue')); + + await screen.findByText('Locked'); + expect(fixtures.signIn.create).toHaveBeenCalledTimes(1); + const passwordField = container.querySelector('#password-field') as HTMLElement; + expect(passwordField.closest('[class*="formFieldRow"]')).not.toHaveAttribute('aria-hidden'); + expect(passwordField).toBeVisible(); + await userEvent.type(passwordField, 'some-password'); + await userEvent.click(screen.getByText('Continue')); + + await waitFor(() => { + expect(fixtures.clerk.setActive).toHaveBeenCalledWith({ + session: 'sess_password', + navigate: expect.any(Function), + }); + }); + expect(fixtures.signIn.create).toHaveBeenCalledTimes(3); + expect(fixtures.signIn.create).toHaveBeenNthCalledWith(2, { identifier: 'hello@clerk.com' }); + expect(fixtures.signIn.create).toHaveBeenNthCalledWith(3, { + identifier: 'hello@clerk.com', + password: 'some-password', + strategy: 'password', + }); + expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled(); + }); + + it.each(['user_locked', 'form_password_incorrect', 'form_password_pwned', 'strategy_for_user_invalid'])( + 'shows %s from a rejected password fallback without an identifier-only retry', + async code => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + f.withEnterpriseSso(); + }); + fixtures.signIn.create.mockRejectedValueOnce( + new ClerkAPIResponseError('Locked', { + data: [{ code: 'user_locked', message: 'Locked', long_message: 'Locked' }], + status: 403, + }), + ); + fixtures.signIn.create.mockRejectedValueOnce( + new ClerkAPIResponseError('Password rejected', { + data: [ + { + code, + message: 'Password rejected', + long_message: 'Password rejected', + meta: { param_name: 'password' }, + }, + ], + status: 422, + }), + ); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + fireEvent.change(container.querySelector('#password-field') as Element, { + target: { value: 'wrong-password' }, + }); + fireEvent.submit(container.querySelector('form') as Element); + + await waitFor(() => expect(fixtures.signIn.create).toHaveBeenCalledTimes(2)); + await waitFor(() => { + expect(container.querySelector('.cl-formFieldErrorText__password')).toHaveTextContent( + code === 'form_password_pwned' ? /breach/ : 'Password rejected', + ); + }); + expect(container.querySelector('#password-field')).toBeVisible(); + expect(fixtures.signIn.create).toHaveBeenCalledTimes(2); + expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled(); + expect(fixtures.clerk.setActive).not.toHaveBeenCalled(); + }, + ); + + it.each([ + { enterpriseSSO: true, password: '', code: 'user_locked' }, + { enterpriseSSO: false, password: 'some-password', code: 'user_locked' }, + { enterpriseSSO: true, password: 'some-password', code: 'user_banned' }, + ])( + 'does not retry creation for $code with enterpriseSSO=$enterpriseSSO and password="$password"', + async testCase => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + if (testCase.enterpriseSSO) { + f.withEnterpriseSso(); + } + }); + fixtures.signIn.create.mockRejectedValueOnce( + new ClerkAPIResponseError('Denied', { + data: [{ code: testCase.code, message: 'Denied', long_message: 'Denied' }], + status: 403, + }), + ); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + if (testCase.password) { + fireEvent.change(container.querySelector('#password-field') as Element, { + target: { value: testCase.password }, + }); + } + fireEvent.submit(container.querySelector('form') as Element); + + await screen.findByText('Denied'); + expect(fixtures.signIn.create).toHaveBeenCalledTimes(1); + expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled(); + expect(fixtures.clerk.setActive).not.toHaveBeenCalled(); + }, + ); + + it('hands off to enterprise SSO without attempting an autofilled password', async () => { + const { wrapper, fixtures } = await createFixtures(f => { + f.withEmailAddress(); + f.withPassword({ required: true }); + f.withEnterpriseSso(); + }); + fixtures.signIn.create.mockResolvedValueOnce({ + status: 'needs_first_factor', + supportedFirstFactors: [{ strategy: 'enterprise_sso' }], + } as unknown as SignInResource); + + const { userEvent, container } = render(, { wrapper }); + await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com'); + fireEvent.change(container.querySelector('#password-field') as Element, { + target: { value: 'some-password' }, + }); + fireEvent.submit(container.querySelector('form') as Element); + + await waitFor(() => { + expect(fixtures.signIn.authenticateWithRedirect).toHaveBeenCalledWith({ + strategy: 'enterprise_sso', + redirectUrl: 'http://localhost:3000/#/sso-callback', + redirectUrlComplete: '/', + continueSignIn: true, + }); + }); + expect(fixtures.signIn.create).toHaveBeenCalledExactlyOnceWith({ identifier: 'hello@clerk.com' }); + expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled(); + expect(fixtures.clerk.setActive).not.toHaveBeenCalled(); + }); + it('initiates a Enterprise SSO flow if enterprise_sso is listed as the only supported first factor', async () => { const { wrapper, fixtures } = await createFixtures(f => { f.withEmailAddress();