The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(auth): validate login password before processing workspace invitation (#26657) (#26742)
PINYO PATTANAWASANPORNc72e258a9ce4
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.tsindex 4df4742884a..7abe66cab66 100644--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts@@ -236,10 +236,11 @@ export class AuthResolver {),);- const user = await this.authService.validateLoginWithPassword(- getLoginTokenFromCredentialsInput,- workspace,- );+ const user =+ await this.authService.validateLoginWithPasswordAndJoinWorkspaceIfInvited(+ getLoginTokenFromCredentialsInput,+ workspace,+ );const loginToken = await this.loginTokenService.generateLoginToken(user.email,diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.tsindex 72ad06950fd..589c39d51ec 100644--- a/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts@@ -25,7 +25,6 @@ import {} from 'src/engine/core-modules/auth/auth.exception';import {PASSWORD_REGEX,- compareHash,hashPassword,} from 'src/engine/core-modules/auth/auth.util';import { type AuthTokens } from 'src/engine/core-modules/auth/dto/auth-tokens.dto';@@ -53,6 +52,7 @@ import {type SignInUpNewUserPayload,} from 'src/engine/core-modules/auth/types/sign-in-up.type';import { assertIssuerIsPublishedOrThrow } from 'src/engine/core-modules/auth/utils/assert-issuer-is-published.util';+import { assertUserPasswordIsValidOrThrow } from 'src/engine/core-modules/auth/utils/assert-user-password-is-valid-or-throw.util';import { validateRedirectUri } from 'src/engine/core-modules/auth/utils/validate-redirect-uri.util';import { DomainServerConfigService } from 'src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service';import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';@@ -70,7 +70,9 @@ import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/useimport { UserService } from 'src/engine/core-modules/user/services/user.service';import { UserEntity } from 'src/engine/core-modules/user/user.entity';import { INVITATION_APP_TOKEN_TYPES } from 'src/engine/core-modules/workspace-invitation/constants/invitation-app-token-types';+import { type WorkspaceInvitation } from 'src/engine/core-modules/workspace-invitation/dtos/workspace-invitation.dto';import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-invitation/services/workspace-invitation.service';+import { castAppTokenToWorkspaceInvitationUtil } from 'src/engine/core-modules/workspace-invitation/utils/cast-app-token-to-workspace-invitation.util';import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { workspaceValidator } from 'src/engine/core-modules/workspace/workspace.validate';@@ -109,56 +111,9 @@ export class AuthService {private readonly userSessionService: UserSessionService,) {}- private async checkAccessAndUseInvitationOrThrow(- workspace: WorkspaceEntity,- user: UserEntity,- ) {- if (- await this.userWorkspaceService.checkUserWorkspaceExists(- user.id,- workspace.id,- )- ) {- return;- }-- const invitation =- await this.workspaceInvitationService.getOneWorkspaceInvitation(- workspace.id,- user.email,- );-- if (invitation) {- await this.workspaceInvitationService.validatePersonalInvitation({- workspacePersonalInviteToken: invitation.value,- email: user.email,- });- await this.userWorkspaceService.addUserToWorkspaceIfUserNotInWorkspace(- user,- workspace,- invitation.context?.roleId,- );-- return;- }-- throw new AuthException(- 'User is not a member of the workspace.',- AuthExceptionCode.FORBIDDEN_EXCEPTION,- {- userFriendlyMessage: msg`User is not a member of the workspace.`,- },- );- }-- async validateLoginWithPassword(- input: UserCredentialsInput,- targetWorkspace?: WorkspaceEntity,- ) {+ private async findUserByEmailOrThrow(email: string) {const user = await this.userRepository.findOne({- where: {- email: input.email,- },+ where: { email },relations: { userWorkspaces: true },});@@ -169,47 +124,111 @@ export class AuthService {);}- if (targetWorkspace && !targetWorkspace.isPasswordAuthEnabled) {- const canBypass = await this.canUserBypassAuthProvider({- user,- workspace: targetWorkspace,- provider: AuthProviderEnum.Password,- });+ return user;+ }- if (!canBypass) {- throw new AuthException(- 'Email/Password auth is not enabled for this workspace',- AuthExceptionCode.FORBIDDEN_EXCEPTION,- );- }+ private async assertPasswordAuthAllowedOnWorkspaceOrThrow(+ user: UserEntity,+ workspace: WorkspaceEntity,+ ) {+ if (workspace.isPasswordAuthEnabled) {+ return;}- if (targetWorkspace) {- await this.checkAccessAndUseInvitationOrThrow(targetWorkspace, user);- }+ const canBypass = await this.canUserBypassAuthProvider({+ user,+ workspace,+ provider: AuthProviderEnum.Password,+ });- if (!user.passwordHash) {+ if (!canBypass) {throw new AuthException(- 'Incorrect login method',- AuthExceptionCode.INVALID_INPUT,- {- userFriendlyMessage: msg`User was not created with email/password`,- },+ 'Email/Password auth is not enabled for this workspace',+ AuthExceptionCode.FORBIDDEN_EXCEPTION,);}+ }- const isValid = await compareHash(input.password, user.passwordHash);+ private async getValidWorkspaceInvitationOrThrow(+ workspace: WorkspaceEntity,+ user: UserEntity,+ ): Promise<WorkspaceInvitation> {+ const invitation =+ await this.workspaceInvitationService.getOneWorkspaceInvitation(+ workspace.id,+ user.email,+ );- if (!isValid) {+ if (!isDefined(invitation)) {throw new AuthException(- 'Wrong password',+ 'User is not a member of the workspace.',AuthExceptionCode.FORBIDDEN_EXCEPTION,{- userFriendlyMessage: msg`Wrong password.`,+ userFriendlyMessage: msg`User is not a member of the workspace.`,},);}+ await this.workspaceInvitationService.validatePersonalInvitation({+ workspacePersonalInviteToken: invitation.value,+ email: user.email,+ });++ return castAppTokenToWorkspaceInvitationUtil(invitation);+ }++ private async validatePasswordCredentialsOrThrow(+ user: UserEntity,+ password: string,+ ) {+ await assertUserPasswordIsValidOrThrow({ user, password });++ await this.checkIsEmailVerified(user.isEmailVerified);+ }++ async validateLoginWithPassword(input: UserCredentialsInput) {+ const user = await this.findUserByEmailOrThrow(input.email);++ await this.validatePasswordCredentialsOrThrow(user, input.password);++ return user;+ }++ async validateLoginWithPasswordAndJoinWorkspaceIfInvited(+ input: UserCredentialsInput,+ workspace: WorkspaceEntity,+ ): Promise<UserEntity> {+ const user = await this.findUserByEmailOrThrow(input.email);++ await this.assertPasswordAuthAllowedOnWorkspaceOrThrow(user, workspace);++ // Access is checked before the password so that a non-member cannot tell a right password from a wrong one+ const isWorkspaceMember =+ await this.userWorkspaceService.checkUserWorkspaceExists(+ user.id,+ workspace.id,+ );++ if (isWorkspaceMember) {+ await this.validatePasswordCredentialsOrThrow(user, input.password);++ return user;+ }++ const workspaceInvitation = await this.getValidWorkspaceInvitationOrThrow(+ workspace,+ user,+ );++ await assertUserPasswordIsValidOrThrow({ user, password: input.password });++ // Joining before the email check lets the user land in this workspace from verifyEmailAndGetLoginToken once their email is verified+ await this.userWorkspaceService.addUserToWorkspaceIfUserNotInWorkspace(+ user,+ workspace,+ workspaceInvitation.roleId,+ );+await this.checkIsEmailVerified(user.isEmailVerified);return user;@@ -241,18 +260,9 @@ export class AuthService {}if (userData.type === 'existingUser') {- if (!userData.existingUser.passwordHash) {- throw new AuthException(- 'Incorrect login method',- AuthExceptionCode.INVALID_INPUT,- {- userFriendlyMessage: msg`User was not created with email/password`,- },- );- }- await this.signInUpService.validatePassword({+ await assertUserPasswordIsValidOrThrow({+ user: userData.existingUser,password: authParams.password,- passwordHash: userData.existingUser.passwordHash,});}}diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.tsindex 3e076b62ba3..14f6183fe4e 100644--- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts@@ -33,7 +33,6 @@ import {} from 'src/engine/core-modules/auth/auth.exception';import {PASSWORD_REGEX,- compareHash,hashPassword,} from 'src/engine/core-modules/auth/auth.util';import { MAX_WORKSPACES_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/auth/constants/max-workspaces-without-organization-key.constants';@@ -179,26 +178,6 @@ export class SignInUpService {return await hashPassword(password);}- async validatePassword({- password,- passwordHash,- }: {- password: string;- passwordHash: string;- }) {- const isValid = await compareHash(password, passwordHash);-- if (!isValid) {- throw new AuthException(- 'Wrong password',- AuthExceptionCode.FORBIDDEN_EXCEPTION,- {- userFriendlyMessage: msg`Wrong password`,- },- );- }- }-private async signInUpWithPersonalInvitation(params: {invitation: AppTokenEntity;diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-user-password-is-valid-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-user-password-is-valid-or-throw.util.spec.tsnew file mode 100644index 00000000000..da8a1173094--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-user-password-is-valid-or-throw.util.spec.ts@@ -0,0 +1,36 @@+import { AuthExceptionCode } from 'src/engine/core-modules/auth/auth.exception';+import { hashPassword } from 'src/engine/core-modules/auth/auth.util';+import { assertUserPasswordIsValidOrThrow } from 'src/engine/core-modules/auth/utils/assert-user-password-is-valid-or-throw.util';++describe('assertUserPasswordIsValidOrThrow', () => {+ it('accepts the right password', async () => {+ const passwordHash = await hashPassword('right-password');++ await expect(+ assertUserPasswordIsValidOrThrow({+ user: { passwordHash },+ password: 'right-password',+ }),+ ).resolves.toBeUndefined();+ });++ it('rejects a wrong password', async () => {+ const passwordHash = await hashPassword('right-password');++ await expect(+ assertUserPasswordIsValidOrThrow({+ user: { passwordHash },+ password: 'wrong-password',+ }),+ ).rejects.toMatchObject({ code: AuthExceptionCode.FORBIDDEN_EXCEPTION });+ });++ it('rejects a user created without a password', async () => {+ await expect(+ assertUserPasswordIsValidOrThrow({+ user: { passwordHash: '' },+ password: 'any-password',+ }),+ ).rejects.toMatchObject({ code: AuthExceptionCode.INVALID_INPUT });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/assert-user-password-is-valid-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/assert-user-password-is-valid-or-throw.util.tsnew file mode 100644index 00000000000..cceed02f85f--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/assert-user-password-is-valid-or-throw.util.ts@@ -0,0 +1,38 @@+import { msg } from '@lingui/core/macro';++import {+ AuthException,+ AuthExceptionCode,+} from 'src/engine/core-modules/auth/auth.exception';+import { compareHash } from 'src/engine/core-modules/auth/auth.util';+import { type UserEntity } from 'src/engine/core-modules/user/user.entity';++export const assertUserPasswordIsValidOrThrow = async ({+ user,+ password,+}: {+ user: Pick<UserEntity, 'passwordHash'>;+ password: string;+}): Promise<void> => {+ if (!user.passwordHash) {+ throw new AuthException(+ 'Incorrect login method',+ AuthExceptionCode.INVALID_INPUT,+ {+ userFriendlyMessage: msg`User was not created with email/password`,+ },+ );+ }++ const isValid = await compareHash(password, user.passwordHash);++ if (!isValid) {+ throw new AuthException(+ 'Wrong password',+ AuthExceptionCode.FORBIDDEN_EXCEPTION,+ {+ userFriendlyMessage: msg`Wrong password.`,+ },+ );+ }+};diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/login-with-personal-invitation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/login-with-personal-invitation.integration-spec.tsnew file mode 100644index 00000000000..16d44dfbdd4--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/auth/login-with-personal-invitation.integration-spec.ts@@ -0,0 +1,126 @@+import { randomUUID } from 'node:crypto';++import { sendInvitations } from 'test/integration/graphql/suites/user-session/utils/send-invitations.util';+import { buildAppleWorkspaceOrigin } from 'test/integration/graphql/utils/build-apple-workspace-origin.util';+import { deleteUser } from 'test/integration/graphql/utils/delete-user.util';+import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';+import { getLoginTokenFromCredentialsQueryFactory } from 'test/integration/graphql/utils/get-login-token-from-credentials.query-factory.util';+import {+ deleteWorkspaceInvitationsByEmail,+ findWorkspaceInvitationsByEmail,+} from 'test/integration/graphql/utils/seed-workspace-invitation.util';+import { signUp } from 'test/integration/graphql/utils/sign-up.util';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';+import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';++const PASSWORD = 'Login-with-invitation-1';++const signUpUser = async (email: string): Promise<string> => {+ const { data } = await signUp({+ input: { email, password: PASSWORD },+ expectToFail: false,+ });++ return data.signUp.tokens.accessOrWorkspaceAgnosticToken.token;+};++const loginOnAppleWorkspace = (email: string, password: string) =>+ makeMetadataApiRequest(+ getLoginTokenFromCredentialsQueryFactory({+ email,+ password,+ origin: buildAppleWorkspaceOrigin(),+ }),+ null,+ );++describe('getLoginTokenFromCredentials with a personal invitation (integration)', () => {+ let email: string;+ let userAccessToken: string;++ beforeEach(async () => {+ email = `invited-login-${randomUUID()}@example.com`;+ userAccessToken = await signUpUser(email);++ await sendInvitations({ input: { emails: [email] }, expectToFail: false });+ });++ afterEach(async () => {+ await deleteWorkspaceInvitationsByEmail({ email });+ await deleteUser({ accessToken: userAccessToken, expectToFail: false });+ });++ it('keeps the invitation and does not join the workspace on a wrong password', async () => {+ const response = await loginOnAppleWorkspace(email, 'wrong-password');++ expect(response.body.data?.getLoginTokenFromCredentials).toBeFalsy();+ expect(response.body.errors[0].message).toBe('Wrong password');+ expect(await findWorkspaceInvitationsByEmail({ email })).toHaveLength(1);+ });++ it('joins the workspace through the invitation on the right password', async () => {+ const response = await loginOnAppleWorkspace(email, PASSWORD);++ expect(response.body.errors).toBeUndefined();+ expect(await findWorkspaceInvitationsByEmail({ email })).toHaveLength(0);++ const { errors } = await getAuthTokensFromLoginToken({+ loginToken:+ response.body.data.getLoginTokenFromCredentials.loginToken.token,+ origin: buildAppleWorkspaceOrigin(),+ expectToFail: false,+ });++ expect(errors).toBeUndefined();+ });++ it('joins the workspace on the right password even when the email still needs verification', async () => {+ await updateConfigVariable({+ input: { key: 'IS_EMAIL_VERIFICATION_REQUIRED', value: true },+ });++ try {+ const response = await loginOnAppleWorkspace(email, PASSWORD);++ expect(response.body.data?.getLoginTokenFromCredentials).toBeFalsy();+ expect(response.body.errors[0].extensions.subCode).toBe(+ 'EMAIL_NOT_VERIFIED',+ );+ expect(await findWorkspaceInvitationsByEmail({ email })).toHaveLength(0);+ } finally {+ await updateConfigVariable({+ input: { key: 'IS_EMAIL_VERIFICATION_REQUIRED', value: false },+ });+ }++ const response = await loginOnAppleWorkspace(email, PASSWORD);++ expect(response.body.errors).toBeUndefined();+ });+});++describe('getLoginTokenFromCredentials without access to the workspace (integration)', () => {+ let email: string;+ let userAccessToken: string;++ beforeAll(async () => {+ email = `outsider-login-${randomUUID()}@example.com`;+ userAccessToken = await signUpUser(email);+ });++ afterAll(async () => {+ await deleteUser({ accessToken: userAccessToken, expectToFail: false });+ });++ it.each([PASSWORD, 'wrong-password'])(+ 'rejects as not a member whatever the password (%s)',+ async (password) => {+ const response = await loginOnAppleWorkspace(email, password);++ expect(response.body.data?.getLoginTokenFromCredentials).toBeFalsy();+ expect(response.body.errors[0].message).toBe(+ 'User is not a member of the workspace.',+ );+ },+ );+});