Skip to content

The open alternative to Salesforce, designed for AI.

fix: harden two-factor authentication against impersonation and OTP guessing (#26583)

Abdul Rahman544cbbe244ad
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx
index 3729f25f449..30df301eb65 100644
--- a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx
@@ -12,6 +12,7 @@ import {
SignInUpStep,
signInUpStepState,
} from '@/auth/states/signInUpStepState';
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
import { useReadCaptchaToken } from '@/captcha/hooks/useReadCaptchaToken';
import { useCaptcha } from '@/client-config/hooks/useCaptcha';
import { ONBOARDING_CONTENT_BLOCK_WIDTH } from '@/onboarding/constants/OnboardingContentBlockWidth';
@@ -198,14 +199,15 @@ export const SignInUpTOTPVerification = () => {
}
await getAuthTokensFromOTP(values.otp, loginToken, captchaToken);
- } catch {
+ } catch (error) {
form.setValue('otp', '');
- enqueueToast({
- variant: 'error',
- children: t`Invalid verification code. Please try again.`,
- dedupeKey: 'invalid-otp-dedupe-key',
- });
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ dedupeKey: 'invalid-otp-dedupe-key',
+ }),
+ );
} finally {
setIsLoading(false);
}
diff --git a/packages/twenty-front/src/modules/auth/utils/__tests__/getTwoFactorAuthenticationErrorToastOptions.test.ts b/packages/twenty-front/src/modules/auth/utils/__tests__/getTwoFactorAuthenticationErrorToastOptions.test.ts
new file mode 100644
index 00000000000..e03489bc8fa
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/utils/__tests__/getTwoFactorAuthenticationErrorToastOptions.test.ts
@@ -0,0 +1,57 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
+
+describe('getTwoFactorAuthenticationErrorToastOptions', () => {
+ it('shows the server message when verification is rate limited', () => {
+ const error = new CombinedGraphQLErrors({
+ errors: [
+ {
+ message: 'Limit reached (10 tokens per 900000 ms)',
+ extensions: {
+ subCode: 'LIMIT_REACHED',
+ userFriendlyMessage: 'Rate limit reached. Please try again later.',
+ },
+ },
+ ],
+ });
+
+ expect(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ dedupeKey: 'invalid-otp-dedupe-key',
+ }),
+ ).toEqual(
+ expect.objectContaining({
+ variant: 'error',
+ children: 'Rate limit reached. Please try again later.',
+ dedupeKey: 'invalid-otp-dedupe-key-LIMIT_REACHED',
+ }),
+ );
+ });
+
+ it('falls back to the invalid code message for a non-GraphQL error', () => {
+ expect(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error: new Error('Network error'),
+ }),
+ ).toEqual({
+ variant: 'error',
+ children: 'Invalid verification code. Please try again.',
+ dedupeKey: undefined,
+ });
+ });
+
+ it('uses the given fallback message for a non-GraphQL error', () => {
+ expect(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error: new Error('Network error'),
+ fallbackMessage: 'Two factor authentication provisioning failed.',
+ }),
+ ).toEqual(
+ expect.objectContaining({
+ children: 'Two factor authentication provisioning failed.',
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-front/src/modules/auth/utils/getTwoFactorAuthenticationErrorToastOptions.ts b/packages/twenty-front/src/modules/auth/utils/getTwoFactorAuthenticationErrorToastOptions.ts
new file mode 100644
index 00000000000..27440ba1a73
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/utils/getTwoFactorAuthenticationErrorToastOptions.ts
@@ -0,0 +1,42 @@
+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type ToastOptions } from 'twenty-ui/components';
+
+const getGraphQLErrorCode = (
+ error: CombinedGraphQLErrors,
+): string | undefined => {
+ const extensions = error.errors[0]?.extensions;
+ const code = extensions?.subCode ?? extensions?.code;
+
+ return isNonEmptyString(code) ? code : undefined;
+};
+
+export const getTwoFactorAuthenticationErrorToastOptions = ({
+ error,
+ fallbackMessage = t`Invalid verification code. Please try again.`,
+ dedupeKey,
+}: {
+ error: unknown;
+ fallbackMessage?: string;
+ dedupeKey?: string;
+}): ToastOptions | undefined => {
+ if (!CombinedGraphQLErrors.is(error)) {
+ return {
+ variant: 'error',
+ children: fallbackMessage,
+ dedupeKey,
+ };
+ }
+
+ const errorCode = getGraphQLErrorCode(error);
+
+ return getToastOptionsFromError({
+ error,
+ dedupeKey:
+ isNonEmptyString(dedupeKey) && isNonEmptyString(errorCode)
+ ? `${dedupeKey}-${errorCode}`
+ : dedupeKey,
+ });
+};
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationSetupForSettingsEffect.tsx b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationSetupForSettingsEffect.tsx
index b33c6cef46d..20c8158169a 100644
--- a/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationSetupForSettingsEffect.tsx
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationSetupForSettingsEffect.tsx
@@ -1,5 +1,6 @@
import { currentUserState } from '@/auth/states/currentUserState';
import { qrCodeState } from '@/auth/states/qrCode';
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useMutation } from '@apollo/client/react';
@@ -41,12 +42,15 @@ export const TwoFactorAuthenticationSetupForSettingsEffect = () => {
initiateOTPProvisioningResult.data
.initiateOTPProvisioningForAuthenticatedUser.uri,
);
- } catch {
- enqueueToast({
- variant: 'error',
- children: t`Two factor authentication provisioning failed.`,
- dedupeKey: 'two-factor-authentication-provisioning-initiation-failed',
- });
+ } catch (error) {
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ fallbackMessage: t`Two factor authentication provisioning failed.`,
+ dedupeKey:
+ 'two-factor-authentication-provisioning-initiation-failed',
+ }),
+ );
}
};
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useTwoFactorVerificationForSettings.ts b/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useTwoFactorVerificationForSettings.ts
index 1fc10dfa22c..c02a872f31b 100644
--- a/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useTwoFactorVerificationForSettings.ts
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useTwoFactorVerificationForSettings.ts
@@ -1,4 +1,5 @@
import { type OTPFormValues } from '@/auth/sign-in-up/hooks/useTwoFactorAuthenticationForm';
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
import { VERIFY_TWO_FACTOR_AUTHENTICATION_METHOD_FOR_AUTHENTICATED_USER } from '@/settings/two-factor-authentication/graphql/mutations/verifyTwoFactorAuthenticationMethod';
import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
import { useMutation } from '@apollo/client/react';
@@ -53,11 +54,8 @@ export const useTwoFactorVerificationForSettings = () => {
});
await handleVerificationSuccess();
- } catch {
- enqueueToast({
- variant: 'error',
- children: t`Invalid verification code. Please try again.`,
- });
+ } catch (error) {
+ enqueueToast(getTwoFactorAuthenticationErrorToastOptions({ error }));
} finally {
setIsLoading(false);
}
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
index f0c066f9b8c..49032384014 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
@@ -84,6 +84,7 @@ import { MessageQueueService } from 'src/engine/core-modules/message-queue/servi
import { type ConfigVariables } from 'src/engine/core-modules/twenty-config/config-variables';
import { ConfigVariableGraphqlApiExceptionFilter } from 'src/engine/core-modules/twenty-config/filters/config-variable-graphql-api-exception.filter';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { ThrottlerGraphqlApiExceptionFilter } from 'src/engine/core-modules/throttler/filters/throttler-graphql-api-exception.filter';
import { TwoFactorAuthenticationExceptionFilter } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter';
import { UsageBreakdownItemDTO } from 'src/engine/core-modules/usage/dtos/usage-breakdown-item.dto';
import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
@@ -110,6 +111,7 @@ import { getAvailableEfforts } from 'src/engine/metadata-modules/ai/ai-models/ut
@UseFilters(
AuthGraphqlApiExceptionFilter,
TwoFactorAuthenticationExceptionFilter,
+ ThrottlerGraphqlApiExceptionFilter,
PreventNestToAutoLogGraphqlErrorsFilter,
ConfigVariableGraphqlApiExceptionFilter,
)
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 b4c378feb3a..9c69c3eb931 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
@@ -52,6 +52,7 @@ import { SignInUpService } from 'src/engine/core-modules/auth/services/sign-in-u
import { AccessTokenService } from 'src/engine/core-modules/auth/token/services/access-token.service';
import { EmailVerificationTokenService } from 'src/engine/core-modules/auth/token/services/email-verification-token.service';
import { LoginTokenService } from 'src/engine/core-modules/auth/token/services/login-token.service';
+import { assertLoginTokenIsNotForImpersonation } from 'src/engine/core-modules/auth/utils/assert-login-token-is-not-for-impersonation.util';
import { RefreshTokenService } from 'src/engine/core-modules/auth/token/services/refresh-token.service';
import { RenewTokenService } from 'src/engine/core-modules/auth/token/services/renew-token.service';
import { SsoExchangeTokenService } from 'src/engine/core-modules/auth/token/services/sso-exchange-token.service';
@@ -416,14 +417,14 @@ export class AuthResolver {
@Args('origin') origin: string,
@Context() context: { req: Request },
): Promise<AuthTokens> {
- const {
- sub: email,
- authProvider,
- workspaceId,
- } = await this.loginTokenService.verifyLoginToken(
+ const loginTokenPayload = await this.loginTokenService.verifyLoginToken(
twoFactorAuthenticationVerificationInput.loginToken,
);
+ assertLoginTokenIsNotForImpersonation(loginTokenPayload);
+
+ const { sub: email, authProvider, workspaceId } = loginTokenPayload;
+
const workspace = await this.validateWorkspaceAccess(origin, workspaceId);
const user = await this.userService.findUserByEmailOrThrow(email);
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-login-token-is-not-for-impersonation.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-login-token-is-not-for-impersonation.util.spec.ts
new file mode 100644
index 00000000000..b76736cb1de
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-login-token-is-not-for-impersonation.util.spec.ts
@@ -0,0 +1,21 @@
+import { AuthException } from 'src/engine/core-modules/auth/auth.exception';
+import { assertLoginTokenIsNotForImpersonation } from 'src/engine/core-modules/auth/utils/assert-login-token-is-not-for-impersonation.util';
+import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
+
+describe('assertLoginTokenIsNotForImpersonation', () => {
+ it('accepts a regular login token', () => {
+ expect(() =>
+ assertLoginTokenIsNotForImpersonation({
+ authProvider: AuthProviderEnum.Password,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a login token issued for impersonation', () => {
+ expect(() =>
+ assertLoginTokenIsNotForImpersonation({
+ authProvider: AuthProviderEnum.Impersonation,
+ }),
+ ).toThrow(AuthException);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/assert-login-token-is-not-for-impersonation.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/assert-login-token-is-not-for-impersonation.util.ts
new file mode 100644
index 00000000000..fcc1e55ba8d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/assert-login-token-is-not-for-impersonation.util.ts
@@ -0,0 +1,17 @@
+import {
+ AuthException,
+ AuthExceptionCode,
+} from 'src/engine/core-modules/auth/auth.exception';
+import { type LoginTokenJwtPayload } from 'src/engine/core-modules/auth/types/login-token-jwt-payload.type';
+import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
+
+export const assertLoginTokenIsNotForImpersonation = (
+ loginTokenPayload: Pick<LoginTokenJwtPayload, 'authProvider'>,
+): void => {
+ if (loginTokenPayload.authProvider === AuthProviderEnum.Impersonation) {
+ throw new AuthException(
+ 'This operation cannot be performed with an impersonation login token',
+ AuthExceptionCode.FORBIDDEN_EXCEPTION,
+ );
+ }
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant.ts b/packages/twenty-server/src/engine/core-modules/throttler/constants/try-consume-token-buckets-script.constant.ts
similarity index 98%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant.ts
rename to packages/twenty-server/src/engine/core-modules/throttler/constants/try-consume-token-buckets-script.constant.ts
index 6920abc70be..feab921459f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/throttler/constants/try-consume-token-buckets-script.constant.ts
@@ -4,7 +4,7 @@ export const TOKEN_BUCKETS_ALLOW_PARTIAL_ARG = '1';
export const TOKEN_BUCKETS_DENY_PARTIAL_ARG = '0';
export const TRY_CONSUME_TOKEN_BUCKETS_SCRIPT: CacheScript = {
- name: 'usage-limit:try-consume-token-buckets',
+ name: 'throttler:try-consume-token-buckets',
source: `
local requestedCost = tonumber(ARGV[1])
local buckets = cjson.decode(ARGV[2])
diff --git a/packages/twenty-server/src/engine/core-modules/throttler/throttler.service.ts b/packages/twenty-server/src/engine/core-modules/throttler/throttler.service.ts
index 3708d5616af..9c9e07f1473 100644
--- a/packages/twenty-server/src/engine/core-modules/throttler/throttler.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/throttler/throttler.service.ts
@@ -7,6 +7,10 @@ import {
ThrottlerException,
ThrottlerExceptionCode,
} from 'src/engine/core-modules/throttler/throttler.exception';
+import {
+ TOKEN_BUCKETS_DENY_PARTIAL_ARG,
+ TRY_CONSUME_TOKEN_BUCKETS_SCRIPT,
+} from 'src/engine/core-modules/throttler/constants/try-consume-token-buckets-script.constant';
@Injectable()
export class ThrottlerService {
@@ -48,6 +52,35 @@ export class ThrottlerService {
return availableTokens - tokensToConsume;
}
+ async atomicTokenBucketThrottleOrThrow({
+ key,
+ maxTokens,
+ timeWindow,
+ }: {
+ key: string;
+ maxTokens: number;
+ timeWindow: number;
+ }): Promise<void> {
+ const [admittedCount] = await this.cacheStorage.runScript<number[]>({
+ script: TRY_CONSUME_TOKEN_BUCKETS_SCRIPT,
+ keys: [key],
+ args: [
+ '1',
+ JSON.stringify([
+ { burst: maxTokens, refill: maxTokens, windowMs: timeWindow },
+ ]),
+ TOKEN_BUCKETS_DENY_PARTIAL_ARG,
+ ],
+ });
+
+ if (admittedCount !== 1) {
+ throw new ThrottlerException(
+ `Limit reached (${maxTokens} tokens per ${timeWindow} ms)`,
+ ThrottlerExceptionCode.LIMIT_REACHED,
+ );
+ }
+ }
+
async consumeTokens(
key: string,
tokensToConsume: number,
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-otp-rate-limit.constant.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-otp-rate-limit.constant.ts
new file mode 100644
index 00000000000..4663e3e822c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-otp-rate-limit.constant.ts
@@ -0,0 +1,3 @@
+export const TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX = 10;
+export const TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_WINDOW_MS =
+ 15 * 60 * 1000;
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts
index e10d915d68e..5b858095055 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts
@@ -5,6 +5,7 @@ import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
+import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
@@ -22,6 +23,7 @@ import { TwoFactorAuthenticationMethodEntity } from './entities/two-factor-authe
MetricsModule,
TokenModule,
SecretEncryptionModule,
+ ThrottlerModule,
TypeOrmModule.forFeature([
UserEntity,
TwoFactorAuthenticationMethodEntity,
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts
index 9f4f7ef7b99..dc66eca952a 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts
@@ -12,7 +12,9 @@ import {
} from 'src/engine/core-modules/auth/auth.exception';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
import { LoginTokenService } from 'src/engine/core-modules/auth/token/services/login-token.service';
+import { assertLoginTokenIsNotForImpersonation } from 'src/engine/core-modules/auth/utils/assert-login-token-is-not-for-impersonation.util';
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
+import { ThrottlerGraphqlApiExceptionFilter } from 'src/engine/core-modules/throttler/filters/throttler-graphql-api-exception.filter';
import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -25,6 +27,7 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
+import { TwoFactorAuthenticationExceptionFilter } from './two-factor-authentication-exception.filter';
import { TwoFactorAuthenticationService } from './two-factor-authentication.service';
import { DeleteTwoFactorAuthenticationMethodInput } from './dto/delete-two-factor-authentication-method.input';
@@ -36,7 +39,12 @@ import { VerifyTwoFactorAuthenticationMethodDTO } from './dto/verify-two-factor-
import { TwoFactorAuthenticationMethodEntity } from './entities/two-factor-authentication-method.entity';
@MetadataResolver()
-@UseFilters(AuthGraphqlApiExceptionFilter, PermissionsGraphqlApiExceptionFilter)
+@UseFilters(
+ AuthGraphqlApiExceptionFilter,
+ PermissionsGraphqlApiExceptionFilter,
+ TwoFactorAuthenticationExceptionFilter,
+ ThrottlerGraphqlApiExceptionFilter,
+)
export class TwoFactorAuthenticationResolver {
constructor(
private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService,
@@ -55,10 +63,13 @@ export class TwoFactorAuthenticationResolver {
initiateTwoFactorAuthenticationProvisioningInput: InitiateTwoFactorAuthenticationProvisioningInput,
@Args('origin') origin: string,
): Promise<InitiateTwoFactorAuthenticationProvisioningDTO> {
- const { sub: userEmail, workspaceId: tokenWorkspaceId } =
- await this.loginTokenService.verifyLoginToken(
- initiateTwoFactorAuthenticationProvisioningInput.loginToken,
- );
+ const loginTokenPayload = await this.loginTokenService.verifyLoginToken(
+ initiateTwoFactorAuthenticationProvisioningInput.loginToken,
+ );
+
+ assertLoginTokenIsNotForImpersonation(loginTokenPayload);
+
+ const { sub: userEmail, workspaceId: tokenWorkspaceId } = loginTokenPayload;
const workspace =
await this.workspaceDomainsService.getWorkspaceByOriginOrDefaultWorkspace(
@@ -103,7 +114,12 @@ export class TwoFactorAuthenticationResolver {
@Mutation(() => InitiateTwoFactorAuthenticationProvisioningDTO)
@UseGuards(
AuthPrincipalGuard({
- userSession: true,
+ userSession: {
+ standard: true,
+ impersonated: false,
+ playground: false,
+ workspaceAgnostic: true,
+ },
apiKey: false,
oauthClient: false,
application: false,
@@ -137,8 +153,8 @@ export class TwoFactorAuthenticationResolver {
AuthPrincipalGuard({
userSession: {
standard: true,
- impersonated: true,
- playground: true,
+ impersonated: false,
+ playground: false,
workspaceAgnostic: false,
},
apiKey: false,
@@ -187,8 +203,8 @@ export class TwoFactorAuthenticationResolver {
AuthPrincipalGuard({
userSession: {
standard: true,
- impersonated: true,
- playground: true,
+ impersonated: false,
+ playground: false,
workspaceAgnostic: false,
},
apiKey: false,
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts
index 3506cee8cbc..1d31b6047ff 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts
@@ -11,10 +11,16 @@ import {
import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
+import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
+import {
+ TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX,
+ TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_WINDOW_MS,
+} from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-otp-rate-limit.constant';
import { TwoFactorAuthenticationMethodEntity } from 'src/engine/core-modules/two-factor-authentication/entities/two-factor-authentication-method.entity';
import { TOTP_DEFAULT_CONFIGURATION } from 'src/engine/core-modules/two-factor-authentication/strategies/otp/totp/constants/totp.strategy.constants';
import { TotpStrategy } from 'src/engine/core-modules/two-factor-authentication/strategies/otp/totp/totp.strategy';
+import { buildTwoFactorAuthenticationOtpRateLimitKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-otp-rate-limit-key.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
@@ -38,6 +44,7 @@ export class TwoFactorAuthenticationService {
private readonly twoFactorAuthenticationMethodRepository: WorkspaceScopedRepository<TwoFactorAuthenticationMethodEntity>,
private readonly userWorkspaceService: UserWorkspaceService,
private readonly secretEncryptionService: SecretEncryptionService,
+ private readonly throttlerService: ThrottlerService,
) {}
private async decryptStoredSecret({
@@ -153,6 +160,12 @@ export class TwoFactorAuthenticationService {
workspaceId: WorkspaceEntity['id'],
twoFactorAuthenticationStrategy: TwoFactorAuthenticationStrategy,
) {
+ await this.throttlerService.atomicTokenBucketThrottleOrThrow({
+ key: buildTwoFactorAuthenticationOtpRateLimitKey({ userId, workspaceId }),
+ maxTokens: TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX,
+ timeWindow: TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_WINDOW_MS,
+ });
+
const userTwoFactorAuthenticationMethod =
await this.twoFactorAuthenticationMethodRepository.findOne(workspaceId, {
where: {
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-otp-rate-limit-key.util.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-otp-rate-limit-key.util.ts
new file mode 100644
index 00000000000..c7975dc8bf2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-otp-rate-limit-key.util.ts
@@ -0,0 +1,7 @@
+export const buildTwoFactorAuthenticationOtpRateLimitKey = ({
+ userId,
+ workspaceId,
+}: {
+ userId: string;
+ workspaceId: string;
+}): string => `two-factor-authentication-otp:${userId}:${workspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts
index dc2bea39a87..0ed007e0e2c 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts
@@ -12,7 +12,7 @@ import {
TOKEN_BUCKETS_ALLOW_PARTIAL_ARG,
TOKEN_BUCKETS_DENY_PARTIAL_ARG,
TRY_CONSUME_TOKEN_BUCKETS_SCRIPT,
-} from 'src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant';
+} from 'src/engine/core-modules/throttler/constants/try-consume-token-buckets-script.constant';
import {
UsageLimitException,
UsageLimitExceptionCode,
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-otp-rate-limit.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-otp-rate-limit.integration-spec.ts
new file mode 100644
index 00000000000..a4ea0faad18
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-otp-rate-limit.integration-spec.ts
@@ -0,0 +1,95 @@
+import IORedis from 'ioredis';
+import { isDefined } from 'twenty-shared/utils';
+import { verifyTwoFactorAuthenticationMethod } from 'test/integration/graphql/utils/verify-two-factor-authentication-method.util';
+
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX } from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-otp-rate-limit.constant';
+import { buildTwoFactorAuthenticationOtpRateLimitKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-otp-rate-limit-key.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+
+const RATE_LIMIT_KEY = buildTwoFactorAuthenticationOtpRateLimitKey({
+ userId: USER_DATA_SEED_IDS.PHIL,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+});
+
+const RATE_LIMIT_CACHE_KEY = `${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineWorkspace}:${RATE_LIMIT_KEY}`;
+
+const clearRateLimitBucket = async (): Promise<void> => {
+ const redis = new IORedis(process.env.REDIS_URL ?? 'redis://localhost:6379');
+
+ try {
+ await redis.del(RATE_LIMIT_CACHE_KEY);
+ } finally {
+ redis.disconnect();
+ }
+};
+
+const isLimitReachedError = (error: {
+ extensions?: { subCode?: string };
+}): boolean => error.extensions?.subCode === 'LIMIT_REACHED';
+
+describe('Two-factor authentication OTP rate limiting (integration)', () => {
+ beforeEach(clearRateLimitBucket);
+ afterAll(clearRateLimitBucket);
+
+ it('admits no more than the limit when attempts arrive concurrently', async () => {
+ const concurrentAttempts = TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX * 2;
+
+ const responses = await Promise.all(
+ Array.from({ length: concurrentAttempts }, () =>
+ verifyTwoFactorAuthenticationMethod({
+ otp: '000000',
+ accessToken: APPLE_PHIL_GUEST_ACCESS_TOKEN,
+ expectToFail: true,
+ }),
+ ),
+ );
+
+ const admittedAttempts = responses.filter(
+ ({ errors }) => !(errors ?? []).some(isLimitReachedError),
+ ).length;
+
+ expect(admittedAttempts).toBe(TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX);
+ });
+
+ it('rejects further attempts once the per-user bucket is spent', async () => {
+ let limitReachedError:
+ | {
+ extensions?: {
+ code?: string;
+ subCode?: string;
+ userFriendlyMessage?: string;
+ };
+ }
+ | undefined;
+ let attemptsBeforeLimit = 0;
+
+ for (
+ let attempt = 0;
+ attempt <= TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX;
+ attempt++
+ ) {
+ const { errors } = await verifyTwoFactorAuthenticationMethod({
+ otp: '000000',
+ accessToken: APPLE_PHIL_GUEST_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ limitReachedError = errors?.find(isLimitReachedError);
+
+ if (isDefined(limitReachedError)) {
+ break;
+ }
+
+ attemptsBeforeLimit++;
+ }
+
+ expect(attemptsBeforeLimit).toBe(
+ TWO_FACTOR_AUTHENTICATION_OTP_RATE_LIMIT_MAX,
+ );
+ expect(limitReachedError?.extensions?.userFriendlyMessage).toBe(
+ 'Rate limit reached. Please try again later.',
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts
new file mode 100644
index 00000000000..c0ea2073030
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts
@@ -0,0 +1,162 @@
+import { deleteTwoFactorAuthenticationMethod } from 'test/integration/graphql/suites/user-session/utils/delete-two-factor-authentication-method.util';
+import { generatePlaygroundToken } from 'test/integration/graphql/suites/user-session/utils/generate-playground-token.util';
+import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';
+import { getAuthTokensFromOtp } from 'test/integration/graphql/utils/get-auth-tokens-from-otp.util';
+import { impersonate } from 'test/integration/graphql/utils/impersonate.util';
+import { initiateOtpProvisioning } from 'test/integration/graphql/utils/initiate-otp-provisioning.util';
+import { initiateOtpProvisioningForAuthenticatedUser } from 'test/integration/graphql/utils/initiate-otp-provisioning-for-authenticated-user.util';
+import { verifyTwoFactorAuthenticationMethod } from 'test/integration/graphql/utils/verify-two-factor-authentication-method.util';
+
+import {
+ type BaseGraphQLError,
+ ErrorCode,
+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+
+const expectImpersonationDenied = (errors: BaseGraphQLError[]) => {
+ expect(errors).toHaveLength(1);
+ expect(errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
+ expect(errors[0].extensions.userFriendlyMessage).toBe(
+ 'You do not have permission to perform this action.',
+ );
+};
+
+const expectImpersonationLoginTokenRejected = (errors: BaseGraphQLError[]) => {
+ expect(errors).toHaveLength(1);
+ expect(errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
+ expect(errors[0].message).toContain('impersonation login token');
+};
+
+const deleteScottTwoFactorAuthenticationMethods = async (): Promise<void> => {
+ await global.testDataSource.query(
+ `DELETE FROM core."twoFactorAuthenticationMethod"
+ WHERE "userWorkspaceId" IN (
+ SELECT id FROM core."userWorkspace" WHERE "userId" = $1
+ )`,
+ [USER_DATA_SEED_IDS.SCOTT],
+ );
+};
+
+describe('Impersonation - two-factor authentication mutations denial (integration)', () => {
+ let impersonationLoginToken: string;
+ let impersonationOrigin: string;
+ let impersonationAccessToken: string;
+
+ beforeAll(async () => {
+ await deleteScottTwoFactorAuthenticationMethods();
+
+ const { data: impersonateData } = await impersonate({
+ userId: USER_DATA_SEED_IDS.SCOTT,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ impersonationLoginToken = impersonateData.impersonate.loginToken.token;
+ impersonationOrigin =
+ impersonateData.impersonate.workspace.workspaceUrls.subdomainUrl;
+
+ const { data: tokensData } = await getAuthTokensFromLoginToken({
+ loginToken: impersonationLoginToken,
+ origin: impersonationOrigin,
+ expectToFail: false,
+ });
+
+ impersonationAccessToken =
+ tokensData.getAuthTokensFromLoginToken.tokens
+ .accessOrWorkspaceAgnosticToken.token;
+ });
+
+ afterAll(deleteScottTwoFactorAuthenticationMethods);
+
+ it('rejects login-time OTP provisioning with an impersonation login token', async () => {
+ const { errors } = await initiateOtpProvisioning({
+ loginToken: impersonationLoginToken,
+ origin: impersonationOrigin,
+ expectToFail: true,
+ });
+
+ expectImpersonationLoginTokenRejected(errors);
+ });
+
+ it('rejects exchanging an OTP for tokens with an impersonation login token', async () => {
+ const { errors } = await getAuthTokensFromOtp({
+ loginToken: impersonationLoginToken,
+ origin: impersonationOrigin,
+ otp: '000000',
+ expectToFail: true,
+ });
+
+ expectImpersonationLoginTokenRejected(errors);
+ });
+
+ it('rejects initiating OTP provisioning while impersonating', async () => {
+ const { errors } = await initiateOtpProvisioningForAuthenticatedUser({
+ accessToken: impersonationAccessToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(errors);
+ });
+
+ it('rejects verifying a two-factor method while impersonating', async () => {
+ const { errors } = await verifyTwoFactorAuthenticationMethod({
+ otp: '123456',
+ accessToken: impersonationAccessToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(errors);
+ });
+
+ it('rejects deleting a two-factor method while impersonating', async () => {
+ const { errors } = await deleteTwoFactorAuthenticationMethod({
+ input: {
+ twoFactorAuthenticationMethodId: '20202020-1111-4a01-8001-000000000004',
+ },
+ token: impersonationAccessToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(errors);
+ });
+
+ it('rejects two-factor mutations with a playground token, which drops the impersonation context', async () => {
+ const { data } = await generatePlaygroundToken({
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const playgroundToken = data.generatePlaygroundToken.token;
+
+ const { errors: provisioningErrors } =
+ await initiateOtpProvisioningForAuthenticatedUser({
+ accessToken: playgroundToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(provisioningErrors);
+
+ const { errors: verificationErrors } =
+ await verifyTwoFactorAuthenticationMethod({
+ otp: '123456',
+ accessToken: playgroundToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(verificationErrors);
+
+ const { errors: deletionErrors } =
+ await deleteTwoFactorAuthenticationMethod({
+ input: {
+ twoFactorAuthenticationMethodId:
+ '20202020-1111-4a01-8001-000000000004',
+ },
+ token: playgroundToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(deletionErrors);
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts b/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts
new file mode 100644
index 00000000000..631fefa8f8f
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts
@@ -0,0 +1,64 @@
+import gql from 'graphql-tag';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';
+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';
+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';
+
+import { type AuthTokens } from 'src/engine/core-modules/auth/dto/auth-tokens.dto';
+
+type GetAuthTokensFromOtpUtilArgs = {
+ loginToken: string;
+ otp: string;
+ origin: string;
+ expectToFail?: boolean;
+};
+
+export const getAuthTokensFromOtp = async ({
+ loginToken,
+ otp,
+ origin,
+ expectToFail,
+}: GetAuthTokensFromOtpUtilArgs): CommonResponseBody<{
+ getAuthTokensFromOTP: AuthTokens;
+}> => {
+ const mutation = gql`
+ mutation GetAuthTokensFromOTP(
+ $loginToken: String!
+ $otp: String!
+ $origin: String!
+ ) {
+ getAuthTokensFromOTP(
+ loginToken: $loginToken
+ otp: $otp
+ origin: $origin
+ ) {
+ tokens {
+ accessOrWorkspaceAgnosticToken {
+ token
+ }
+ }
+ }
+ }
+ `;
+
+ const response = await makeMetadataApiRequest(
+ { query: mutation, variables: { loginToken, otp, origin } },
+ null,
+ );
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage: 'OTP token exchange should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage: 'OTP token exchange has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};
diff --git a/packages/twenty-server/test/integration/graphql/utils/initiate-otp-provisioning.util.ts b/packages/twenty-server/test/integration/graphql/utils/initiate-otp-provisioning.util.ts
new file mode 100644
index 00000000000..a2355fc6f79
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/initiate-otp-provisioning.util.ts
@@ -0,0 +1,50 @@
+import gql from 'graphql-tag';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';
+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';
+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';
+
+import { type InitiateTwoFactorAuthenticationProvisioningDTO } from 'src/engine/core-modules/two-factor-authentication/dto/initiate-two-factor-authentication-provisioning.dto';
+
+type InitiateOtpProvisioningUtilArgs = {
+ loginToken: string;
+ origin: string;
+ expectToFail?: boolean;
+};
+
+export const initiateOtpProvisioning = async ({
+ loginToken,
+ origin,
+ expectToFail,
+}: InitiateOtpProvisioningUtilArgs): CommonResponseBody<{
+ initiateOTPProvisioning: InitiateTwoFactorAuthenticationProvisioningDTO;
+}> => {
+ const mutation = gql`
+ mutation InitiateOTPProvisioning($loginToken: String!, $origin: String!) {
+ initiateOTPProvisioning(loginToken: $loginToken, origin: $origin) {
+ uri
+ }
+ }
+ `;
+
+ const response = await makeMetadataApiRequest(
+ { query: mutation, variables: { loginToken, origin } },
+ null,
+ );
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage: 'OTP provisioning should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage: 'OTP provisioning has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};