Skip to content

The open alternative to Salesforce, designed for AI.

Refuse a two-factor code that was already accepted (#29404)

Ayesha Waseemaae53e34b119
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-used-otp.constant.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-used-otp.constant.ts
new file mode 100644
index 00000000000..3a5ac3222ee
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-used-otp.constant.ts
@@ -0,0 +1,6 @@
+import { TOTP_DEFAULT_CONFIGURATION } from 'src/engine/core-modules/two-factor-authentication/strategies/otp/totp/constants/totp.strategy.constants';
+
+export const TWO_FACTOR_AUTHENTICATION_USED_OTP_TTL_MS =
+ (2 * TOTP_DEFAULT_CONFIGURATION.window + 2) *
+ TOTP_DEFAULT_CONFIGURATION.step *
+ 1000;
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 e6f4ff965dc..a29fb5b25fe 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
@@ -17,6 +17,9 @@ import {
AuthExceptionCode,
} from 'src/engine/core-modules/auth/auth.exception';
import { acquireUserAuthenticationLock } from 'src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util';
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
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';
@@ -26,10 +29,12 @@ 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 { TWO_FACTOR_AUTHENTICATION_USED_OTP_TTL_MS } from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-used-otp.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 { buildTwoFactorAuthenticationUsedOtpKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-used-otp-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';
@@ -56,6 +61,8 @@ export class TwoFactorAuthenticationService {
private readonly userWorkspaceService: UserWorkspaceService,
private readonly secretEncryptionService: SecretEncryptionService,
private readonly throttlerService: ThrottlerService,
+ @InjectCacheStorage(CacheStorageNamespace.EngineAuthSession)
+ private readonly cacheStorage: CacheStorageService,
) {}
private async decryptStoredSecret({
@@ -244,6 +251,22 @@ export class TwoFactorAuthenticationService {
);
}
+ const isFirstUseOfToken = await this.cacheStorage.setIfAbsent(
+ buildTwoFactorAuthenticationUsedOtpKey({
+ methodId: userTwoFactorAuthenticationMethod.id,
+ token,
+ }),
+ true,
+ TWO_FACTOR_AUTHENTICATION_USED_OTP_TTL_MS,
+ );
+
+ if (!isFirstUseOfToken) {
+ throw new TwoFactorAuthenticationException(
+ 'Invalid OTP',
+ TwoFactorAuthenticationExceptionCode.INVALID_OTP,
+ );
+ }
+
await this.appTokenRepository.manager.transaction(async (entityManager) => {
await acquireUserAuthenticationLock({
entityManager,
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-used-otp-key.util.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-used-otp-key.util.ts
new file mode 100644
index 00000000000..4c0e6197be9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-used-otp-key.util.ts
@@ -0,0 +1,7 @@
+export const buildTwoFactorAuthenticationUsedOtpKey = ({
+ methodId,
+ token,
+}: {
+ methodId: string;
+ token: string;
+}): string => `two-factor-authentication-used-otp:${methodId}:${token}`;
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts
index 32c49f8445b..3ac08afc5dc 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts
@@ -20,6 +20,7 @@ import { acquireUserAuthenticationLock } from 'src/engine/core-modules/auth/util
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { TOKEN_BUCKET_THROTTLE_KEY_PREFIX } from 'src/engine/core-modules/throttler/constants/token-bucket-throttle-key-prefix.constant';
import { TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX } from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant';
+import { buildTwoFactorAuthenticationUsedOtpKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-used-otp-key.util';
import { hashTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util';
import { UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
import {
@@ -47,12 +48,37 @@ const waitUntilSafelyInsideTotpStep = async (): Promise<void> => {
}
};
+const clearUsedOtps = async (): Promise<void> => {
+ const redis = new IORedis(process.env.REDIS_URL ?? 'redis://localhost:6379');
+
+ try {
+ const keys = await redis.keys(
+ `${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineAuthSession}:${buildTwoFactorAuthenticationUsedOtpKey({ methodId: '*', token: '*' })}`,
+ );
+
+ if (keys.length > 0) {
+ await redis.del(...keys);
+ }
+ } finally {
+ redis.disconnect();
+ }
+};
+
const generateOtp = async (secret: string): Promise<string> => {
await waitUntilSafelyInsideTotpStep();
+ await clearUsedOtps();
return authenticator.generate(secret);
};
+const generatePreviousStepOtp = async (secret: string): Promise<string> => {
+ await waitUntilSafelyInsideTotpStep();
+
+ return authenticator
+ .clone({ epoch: Date.now() - TOTP_STEP_DURATION_MS })
+ .generate(secret);
+};
+
const clearTwoFactorAuthenticationRateLimits = async (): Promise<void> => {
const redis = new IORedis(process.env.REDIS_URL ?? 'redis://localhost:6379');
@@ -455,10 +481,13 @@ describe('Two-factor authentication recovery codes (integration)', () => {
});
it('leaves exactly one usable code when two are issued at the same time', async () => {
- const otp = await generateOtp(janeSecret);
+ const otps = [
+ await generateOtp(janeSecret),
+ await generatePreviousStepOtp(janeSecret),
+ ];
const responses = await Promise.all(
- [0, 1].map(() =>
+ otps.map((otp) =>
generateTwoFactorAuthenticationRecoveryCode({
userId: USER_DATA_SEED_IDS.JONY,
otp,
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts
index a4a63c1e1e4..1ad6530bd91 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts
@@ -1,9 +1,22 @@
+import IORedis from 'ioredis';
import { authenticator } from 'otplib';
+import { buildAppleWorkspaceOrigin } from 'test/integration/graphql/utils/build-apple-workspace-origin.util';
+import { getAuthTokensFromOtp } from 'test/integration/graphql/utils/get-auth-tokens-from-otp.util';
+import { getLoginTokenFromCredentialsQueryFactory } from 'test/integration/graphql/utils/get-login-token-from-credentials.query-factory.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 { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { TOKEN_BUCKET_THROTTLE_KEY_PREFIX } from 'src/engine/core-modules/throttler/constants/token-bucket-throttle-key-prefix.constant';
+import { buildTwoFactorAuthenticationOtpRateLimitKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-otp-rate-limit-key.util';
+import { buildTwoFactorAuthenticationUsedOtpKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-used-otp-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';
import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+const JONY_EMAIL = '[email protected]';
+const SEEDED_PASSWORD = '[email protected]';
const TOTP_STEP_DURATION_MS = 30_000;
const MINIMUM_STEP_REMAINING_MS = 5_000;
@@ -22,6 +35,19 @@ const waitUntilSafelyInsideTotpStep = async (): Promise<void> => {
}
};
+const getJonyLoginToken = async (): Promise<string> => {
+ const response = await makeMetadataApiRequest(
+ getLoginTokenFromCredentialsQueryFactory({
+ email: JONY_EMAIL,
+ password: SEEDED_PASSWORD,
+ origin: buildAppleWorkspaceOrigin(),
+ }),
+ null,
+ );
+
+ return response.body.data.getLoginTokenFromCredentials.loginToken.token;
+};
+
const deleteJonyTwoFactorAuthenticationMethods = async (): Promise<void> => {
await global.testDataSource.query(
`DELETE FROM core."twoFactorAuthenticationMethod" WHERE "userWorkspaceId" = $1`,
@@ -29,6 +55,27 @@ const deleteJonyTwoFactorAuthenticationMethods = async (): Promise<void> => {
);
};
+const USED_OTP_CACHE_KEY_PATTERN = `${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineAuthSession}:${buildTwoFactorAuthenticationUsedOtpKey({ methodId: '*', token: '*' })}`;
+
+const RATE_LIMIT_CACHE_KEY = `${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineWorkspace}:${TOKEN_BUCKET_THROTTLE_KEY_PREFIX}:${buildTwoFactorAuthenticationOtpRateLimitKey(
+ {
+ userId: USER_DATA_SEED_IDS.JONY,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ },
+)}`;
+
+const clearUsedOtpsAndRateLimit = async (): Promise<void> => {
+ const redis = new IORedis(process.env.REDIS_URL ?? 'redis://localhost:6379');
+
+ try {
+ const keys = await redis.keys(USED_OTP_CACHE_KEY_PATTERN);
+
+ await redis.del(RATE_LIMIT_CACHE_KEY, ...keys);
+ } finally {
+ redis.disconnect();
+ }
+};
+
describe('Two-factor authentication TOTP verification (integration)', () => {
let secret: string;
@@ -55,8 +102,65 @@ describe('Two-factor authentication TOTP verification (integration)', () => {
secret = secretFromUri;
});
+ beforeEach(clearUsedOtpsAndRateLimit);
+
afterAll(async () => {
await deleteJonyTwoFactorAuthenticationMethods();
+ await clearUsedOtpsAndRateLimit();
+ });
+
+ it('should reject a code that was already accepted', async () => {
+ await waitUntilSafelyInsideTotpStep();
+
+ const token = generateTokenAtEpoch(secret, Date.now());
+
+ const firstUse = await verifyTwoFactorAuthenticationMethod({
+ otp: token,
+ accessToken: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ expect(firstUse.errors).toBeUndefined();
+ expect(
+ firstUse.data.verifyTwoFactorAuthenticationMethodForAuthenticatedUser
+ .success,
+ ).toBe(true);
+
+ const replay = await verifyTwoFactorAuthenticationMethod({
+ otp: token,
+ accessToken: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(replay.errors?.[0]?.extensions?.subCode).toBe('INVALID_OTP');
+ expect(
+ replay.data?.verifyTwoFactorAuthenticationMethodForAuthenticatedUser,
+ ).toBeFalsy();
+ });
+
+ it('should accept a code only once when it is submitted concurrently', async () => {
+ await waitUntilSafelyInsideTotpStep();
+
+ const token = generateTokenAtEpoch(secret, Date.now());
+
+ const responses = await Promise.all(
+ Array.from({ length: 3 }, () =>
+ verifyTwoFactorAuthenticationMethod({
+ otp: token,
+ accessToken: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ }),
+ ),
+ );
+
+ const acceptedAttempts = responses.filter(
+ ({ errors }) => errors === undefined,
+ ).length;
+ const rejectedSubCodes = responses.flatMap(
+ ({ errors }) => errors?.map((error) => error.extensions?.subCode) ?? [],
+ );
+
+ expect(acceptedAttempts).toBe(1);
+ expect(rejectedSubCodes).toEqual(['INVALID_OTP', 'INVALID_OTP']);
});
it('should reject a code that is more than one step old', async () => {
@@ -113,4 +217,33 @@ describe('Two-factor authentication TOTP verification (integration)', () => {
data.verifyTwoFactorAuthenticationMethodForAuthenticatedUser.success,
).toBe(true);
});
+
+ it('should reject a code that was already used to sign in', async () => {
+ await waitUntilSafelyInsideTotpStep();
+
+ const token = generateTokenAtEpoch(secret, Date.now());
+
+ const firstSignIn = await getAuthTokensFromOtp({
+ loginToken: await getJonyLoginToken(),
+ otp: token,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ expect(firstSignIn.errors).toBeUndefined();
+ expect(
+ firstSignIn.data.getAuthTokensFromOTP.tokens
+ .accessOrWorkspaceAgnosticToken.token,
+ ).toBeDefined();
+
+ const replay = await getAuthTokensFromOtp({
+ loginToken: await getJonyLoginToken(),
+ otp: token,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(replay.errors?.[0]?.extensions?.subCode).toBe('INVALID_OTP');
+ expect(replay.data?.getAuthTokensFromOTP).toBeFalsy();
+ });
});