Skip to content

The open alternative to Salesforce, designed for AI.

Fix auth provider propagation in password sign-up flows (#25078)

Félix Malfait1c6e661ed0b4
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts
index 00a7fc0606d..9bada853b33 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts
@@ -4,6 +4,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';
import { ApiKeyService } from 'src/engine/core-modules/api-key/services/api-key.service';
import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
+import { AuthExceptionCode } from 'src/engine/core-modules/auth/auth.exception';
import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
import { ImpersonationAuthorizationService } from 'src/engine/core-modules/impersonation/services/impersonation-authorization.service';
import { SignInUpService } from 'src/engine/core-modules/auth/services/sign-in-up.service';
@@ -33,6 +34,7 @@ import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
+import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
import { AuthResolver } from './auth.resolver';
@@ -46,8 +48,31 @@ import { TransientTokenService } from './token/services/transient-token.service'
describe('AuthResolver', () => {
let resolver: AuthResolver;
+ let appTokenRepository: { remove: jest.Mock };
+ let authService: {
+ checkAccessForSignIn: jest.Mock;
+ findWorkspaceForSignInUp: jest.Mock;
+ formatUserDataPayload: jest.Mock;
+ signInUp: jest.Mock;
+ };
+ let emailVerificationService: { sendVerificationEmail: jest.Mock };
+ let emailVerificationTokenService: {
+ validateEmailVerificationTokenOrThrow: jest.Mock;
+ };
+ let loginTokenService: { generateLoginToken: jest.Mock };
let resetPasswordService: ResetPasswordService;
+ let signInUpService: { signUpOnNewWorkspace: jest.Mock };
let throttlerService: ThrottlerService;
+ let userService: {
+ findUserByEmail: jest.Mock;
+ findUserByIdOrThrow: jest.Mock;
+ markEmailAsVerified: jest.Mock;
+ };
+ let workspaceDomainsService: {
+ buildWorkspaceURL: jest.Mock;
+ getWorkspaceByOriginOrDefaultWorkspace: jest.Mock;
+ getWorkspaceUrls: jest.Mock;
+ };
const mock_CaptchaGuard: CanActivate = { canActivate: jest.fn(() => true) };
beforeEach(async () => {
@@ -56,7 +81,9 @@ describe('AuthResolver', () => {
AuthResolver,
{
provide: getRepositoryToken(AppTokenEntity),
- useValue: {},
+ useValue: {
+ remove: jest.fn(),
+ },
},
{
provide: getRepositoryToken(UserEntity),
@@ -68,7 +95,12 @@ describe('AuthResolver', () => {
},
{
provide: AuthService,
- useValue: {},
+ useValue: {
+ checkAccessForSignIn: jest.fn(),
+ findWorkspaceForSignInUp: jest.fn(),
+ formatUserDataPayload: jest.fn(),
+ signInUp: jest.fn(),
+ },
},
{
provide: RefreshTokenService,
@@ -76,7 +108,11 @@ describe('AuthResolver', () => {
},
{
provide: UserService,
- useValue: {},
+ useValue: {
+ findUserByEmail: jest.fn(),
+ findUserByIdOrThrow: jest.fn(),
+ markEmailAsVerified: jest.fn(),
+ },
},
{
provide: WorkspaceDomainsService,
@@ -84,6 +120,8 @@ describe('AuthResolver', () => {
buildWorkspaceURL: jest
.fn()
.mockResolvedValue(new URL('http://localhost:3001')),
+ getWorkspaceByOriginOrDefaultWorkspace: jest.fn(),
+ getWorkspaceUrls: jest.fn(),
},
},
{
@@ -96,7 +134,9 @@ describe('AuthResolver', () => {
},
{
provide: UserSessionService,
- useValue: {},
+ useValue: {
+ issueSessionForTokenPair: jest.fn(),
+ },
},
{
provide: UserSessionCookieService,
@@ -104,7 +144,11 @@ describe('AuthResolver', () => {
},
{
provide: UserWorkspaceService,
- useValue: {},
+ useValue: {
+ findAvailableWorkspacesByEmail: jest.fn(),
+ findFirstWorkspaceByUserId: jest.fn(),
+ setLoginTokenToAvailableWorkspacesWhenAuthProviderMatch: jest.fn(),
+ },
},
{
provide: RenewTokenService,
@@ -112,7 +156,9 @@ describe('AuthResolver', () => {
},
{
provide: SignInUpService,
- useValue: {},
+ useValue: {
+ signUpOnNewWorkspace: jest.fn(),
+ },
},
{
provide: ApiKeyService,
@@ -138,11 +184,15 @@ describe('AuthResolver', () => {
},
{
provide: LoginTokenService,
- useValue: {},
+ useValue: {
+ generateLoginToken: jest.fn(),
+ },
},
{
provide: WorkspaceAgnosticTokenService,
- useValue: {},
+ useValue: {
+ generateWorkspaceAgnosticToken: jest.fn(),
+ },
},
{
provide: SSOExchangeTokenService,
@@ -154,11 +204,15 @@ describe('AuthResolver', () => {
},
{
provide: EmailVerificationService,
- useValue: {},
+ useValue: {
+ sendVerificationEmail: jest.fn(),
+ },
},
{
provide: EmailVerificationTokenService,
- useValue: {},
+ useValue: {
+ validateEmailVerificationTokenOrThrow: jest.fn(),
+ },
},
{
provide: ImpersonationAuthorizationService,
@@ -199,15 +253,108 @@ describe('AuthResolver', () => {
.compile();
resolver = module.get<AuthResolver>(AuthResolver);
+ appTokenRepository = module.get(getRepositoryToken(AppTokenEntity));
+ authService = module.get(AuthService);
+ emailVerificationService = module.get(EmailVerificationService);
+ emailVerificationTokenService = module.get(EmailVerificationTokenService);
+ loginTokenService = module.get(LoginTokenService);
resetPasswordService =
module.get<ResetPasswordService>(ResetPasswordService);
+ signInUpService = module.get(SignInUpService);
throttlerService = module.get<ThrottlerService>(ThrottlerService);
+ userService = module.get(UserService);
+ workspaceDomainsService = module.get(WorkspaceDomainsService);
});
it('should be defined', () => {
expect(resolver).toBeDefined();
});
+ describe('password authentication provider propagation', () => {
+ const user = { id: 'user-id', email: '[email protected]' };
+ const workspace = { id: 'workspace-id' };
+ const loginToken = {
+ token: 'login-token',
+ expiresAt: new Date('2026-01-01T00:00:00.000Z'),
+ };
+
+ it('uses the password provider when verifying an email on a workspace domain', async () => {
+ const appToken = { user, context: {} };
+
+ emailVerificationTokenService.validateEmailVerificationTokenOrThrow.mockResolvedValue(
+ appToken,
+ );
+ userService.markEmailAsVerified.mockResolvedValue(user);
+ workspaceDomainsService.getWorkspaceByOriginOrDefaultWorkspace.mockResolvedValue(
+ workspace,
+ );
+ workspaceDomainsService.getWorkspaceUrls.mockReturnValue({
+ subdomainUrl: 'https://workspace.example.com',
+ });
+ loginTokenService.generateLoginToken.mockResolvedValue(loginToken);
+
+ await resolver.verifyEmailAndGetLoginToken(
+ {
+ email: user.email,
+ emailVerificationToken: 'email-verification-token',
+ },
+ 'https://workspace.example.com',
+ );
+
+ expect(loginTokenService.generateLoginToken).toHaveBeenCalledWith(
+ user.email,
+ workspace.id,
+ AuthProviderEnum.Password,
+ );
+ expect(appTokenRepository.remove).toHaveBeenCalledWith(appToken);
+ });
+
+ it('uses the password provider when signing up in a workspace', async () => {
+ authService.findWorkspaceForSignInUp.mockResolvedValue(workspace);
+ userService.findUserByEmail.mockResolvedValue(null);
+ authService.formatUserDataPayload.mockReturnValue({
+ userData: { type: 'newUser' },
+ });
+ authService.signInUp.mockResolvedValue({ user, workspace });
+ loginTokenService.generateLoginToken.mockResolvedValue(loginToken);
+ workspaceDomainsService.getWorkspaceUrls.mockReturnValue({
+ subdomainUrl: 'https://workspace.example.com',
+ });
+
+ await resolver.signUpInWorkspace({
+ email: user.email,
+ password: 'password',
+ });
+
+ expect(emailVerificationService.sendVerificationEmail).toHaveBeenCalled();
+ expect(loginTokenService.generateLoginToken).toHaveBeenCalledWith(
+ user.email,
+ workspace.id,
+ AuthProviderEnum.Password,
+ );
+ });
+
+ it('rejects a missing provider before creating a new workspace', async () => {
+ let caughtError: unknown;
+
+ try {
+ await resolver.signUpInNewWorkspace(
+ { id: user.id } as never,
+ undefined as never,
+ );
+ } catch (error) {
+ caughtError = error;
+ }
+
+ expect(caughtError).toMatchObject({
+ code: AuthExceptionCode.UNAUTHENTICATED,
+ });
+
+ expect(userService.findUserByIdOrThrow).not.toHaveBeenCalled();
+ expect(signInUpService.signUpOnNewWorkspace).not.toHaveBeenCalled();
+ });
+ });
+
describe('emailPasswordResetLink', () => {
const emailPasswordResetInput = {
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.ts
index 4c2014cb2b6..47a99ca2354 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
@@ -294,7 +294,6 @@ export class AuthResolver {
@Args()
getAuthTokenFromEmailVerificationTokenInput: GetAuthTokenFromEmailVerificationTokenInput,
@Args('origin') origin: string,
- @AuthProvider() authProvider: AuthProviderEnum,
) {
const appToken =
await this.emailVerificationTokenService.validateEmailVerificationTokenOrThrow(
@@ -324,7 +323,7 @@ export class AuthResolver {
const loginToken = await this.loginTokenService.generateLoginToken(
user.email,
workspace.id,
- authProvider,
+ AuthProviderEnum.Password,
);
const workspaceUrls =
@@ -338,7 +337,6 @@ export class AuthResolver {
async verifyEmailAndGetWorkspaceAgnosticToken(
@Args()
getAuthTokenFromEmailVerificationTokenInput: GetAuthTokenFromEmailVerificationTokenInput,
- @AuthProvider() authProvider: AuthProviderEnum,
@Context() context: { req: Request },
) {
const appToken =
@@ -370,7 +368,7 @@ export class AuthResolver {
await this.userWorkspaceService.setLoginTokenToAvailableWorkspacesWhenAuthProviderMatch(
availableWorkspaces,
user,
- authProvider,
+ AuthProviderEnum.Password,
),
tokens: {
accessOrWorkspaceAgnosticToken:
@@ -506,7 +504,6 @@ export class AuthResolver {
@UseGuards(CaptchaGuard, PublicEndpointGuard, NoPermissionGuard)
async signUpInWorkspace(
@Args() signUpInput: SignUpInput,
- @AuthProvider() authProvider: AuthProviderEnum,
): Promise<SignUpDTO> {
const currentWorkspace = await this.authService.findWorkspaceForSignInUp({
workspaceInviteHash: signUpInput.workspaceInviteHash,
@@ -564,7 +561,7 @@ export class AuthResolver {
const loginToken = await this.loginTokenService.generateLoginToken(
user.email,
workspace.id,
- authProvider,
+ AuthProviderEnum.Password,
);
return {
@@ -603,6 +600,14 @@ export class AuthResolver {
@AuthProvider() authProvider: AuthProviderEnum,
@Args('input', { nullable: true }) input?: SignUpInNewWorkspaceInput,
): Promise<SignUpDTO> {
+ assertIsDefinedOrThrow(
+ authProvider,
+ new AuthException(
+ 'Authentication provider is missing',
+ AuthExceptionCode.UNAUTHENTICATED,
+ ),
+ );
+
const fullUser = await this.userService.findUserByIdOrThrow(currentUser.id);
const { user, workspace } = await this.signInUpService.signUpOnNewWorkspace(
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.spec.ts
new file mode 100644
index 00000000000..fbcda789387
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.spec.ts
@@ -0,0 +1,49 @@
+import { AuthExceptionCode } from 'src/engine/core-modules/auth/auth.exception';
+import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+
+import { LoginTokenService } from './login-token.service';
+
+describe('LoginTokenService', () => {
+ const jwtWrapperService = {
+ decode: jest.fn(),
+ signAsyncOrThrow: jest.fn(),
+ verifyJwtToken: jest.fn(),
+ };
+ const twentyConfigService = {
+ get: jest.fn().mockReturnValue('1h'),
+ };
+ const service = new LoginTokenService(
+ jwtWrapperService as never,
+ twentyConfigService as never,
+ );
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('does not generate a login token without an authentication provider', async () => {
+ await expect(
+ service.generateLoginToken(
+ 'workspace-id',
+ undefined as never,
+ ),
+ ).rejects.toMatchObject({ code: AuthExceptionCode.INVALID_INPUT });
+
+ expect(jwtWrapperService.signAsyncOrThrow).not.toHaveBeenCalled();
+ });
+
+ it('rejects a login token without an authentication provider', async () => {
+ jwtWrapperService.decode.mockReturnValue({
+ type: JwtTokenTypeEnum.LOGIN,
+ workspaceId: 'workspace-id',
+ });
+
+ await expect(service.verifyLoginToken('login-token')).rejects.toMatchObject(
+ {
+ code: AuthExceptionCode.UNAUTHENTICATED,
+ },
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts
index a842d3635c0..183aa6a37f2 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts
@@ -12,7 +12,7 @@ import { type LoginTokenJwtPayload } from 'src/engine/core-modules/auth/types/lo
import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { type AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
+import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
@Injectable()
export class LoginTokenService {
@@ -27,6 +27,13 @@ export class LoginTokenService {
authProvider: AuthProviderEnum,
options?: { impersonatorUserWorkspaceId?: string },
): Promise<AuthToken> {
+ if (!Object.values(AuthProviderEnum).includes(authProvider)) {
+ throw new AuthException(
+ 'Authentication provider is required to generate a login token',
+ AuthExceptionCode.INVALID_INPUT,
+ );
+ }
+
const jwtPayload: LoginTokenJwtPayload = {
type: JwtTokenTypeEnum.LOGIN,
sub: email,
@@ -62,6 +69,13 @@ export class LoginTokenService {
);
}
+ if (!Object.values(AuthProviderEnum).includes(decoded.authProvider)) {
+ throw new AuthException(
+ 'Login token has an invalid authentication provider',
+ AuthExceptionCode.UNAUTHENTICATED,
+ );
+ }
+
return decoded;
}
}