Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

fix(backend:auth): update failed login attempts atomically

johaven285b8707b0e9
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.ts
index 158cf29d..5ec41dc4 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -1,6 +1,7 @@
import { HttpStatus } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
import bcrypt from 'bcryptjs'
+import { SQL } from 'drizzle-orm'
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
@@ -258,38 +259,51 @@ describe(UsersManager.name, () => {
usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)
await expect(usersManager.updateNotification(userTest, { notification: 2 })).resolves.toBeUndefined()
- const prevAccess1 = new Date('2021-01-01T00:00:00Z')
- const u1 = new UserModel(
- { ...generateUserTest(), isActive: true, passwordAttempts: 3, currentIp: '1.2.3.4', currentAccess: prevAccess1 } as any,
- false
- )
- usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)
+ const u1 = new UserModel({ ...generateUserTest(), isActive: true, passwordAttempts: 3 } as any, false)
+ usersQueriesService.updateAccesses = vi.fn().mockResolvedValue(true)
await expect(usersManager.updateAccesses(u1, '5.6.7.8', true)).resolves.toBeUndefined()
- const payload1 = vi.mocked(usersQueriesService.updateUserOrGuest).mock.calls[0][1]
- expect(payload1).toMatchObject({ lastIp: '1.2.3.4', currentIp: '5.6.7.8', passwordAttempts: 0, isActive: true })
- expect(payload1.lastAccess).toBe(prevAccess1)
- expect(payload1.currentAccess).toBeInstanceOf(Date)
+ expect(usersQueriesService.updateAccesses).toHaveBeenCalledWith(u1.id, '5.6.7.8', 'reset')
- const prevAccess2 = new Date('2022-02-02T00:00:00Z')
const u2 = new UserModel(
{
...generateUserTest(),
isActive: true,
- passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS - 1,
- currentIp: 'old.ip',
- currentAccess: prevAccess2
+ passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS - 1
} as any,
false
)
- usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)
+ usersQueriesService.updateAccesses = vi.fn().mockResolvedValue(true)
await expect(usersManager.updateAccesses(u2, 'new.ip', false)).resolves.toBeUndefined()
- const payload2 = vi.mocked(usersQueriesService.updateUserOrGuest).mock.calls[0][1]
- expect(payload2.passwordAttempts).toBe(USER_MAX_PASSWORD_ATTEMPTS)
- expect(payload2.isActive).toBe(false)
- expect(payload2.lastAccess).toBe(prevAccess2)
- expect(payload2.lastIp).toBe('old.ip')
- expect(payload2.currentIp).toBe('new.ip')
- expect(payload2.currentAccess).toBeInstanceOf(Date)
+ expect(usersQueriesService.updateAccesses).toHaveBeenCalledWith(u2.id, 'new.ip', 'increment')
+
+ const u3 = new UserModel({ ...generateUserTest(), secrets: { twoFaSecret: 'secret' } } as any, false)
+ await expect(usersManager.updateAccesses(u3, 'new.ip', true)).resolves.toBeUndefined()
+ expect(usersQueriesService.updateAccesses).toHaveBeenCalledWith(u3.id, 'new.ip', 'preserve')
+
+ usersQueriesService.updateAccesses = vi.fn().mockResolvedValue(false)
+ await expect(usersManager.updateAccesses(u1, 'new.ip', false)).rejects.toThrow('Unable to update user accesses')
+ })
+
+ it('should update password attempts atomically', async () => {
+ const where = vi.fn().mockResolvedValue([{ affectedRows: 1 }])
+ const set = vi.fn().mockReturnValue({ where })
+ const update = vi.fn().mockReturnValue({ set })
+ const usersQueries = new UsersQueries({ update } as any, {} as Cache)
+
+ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'increment')).resolves.toBe(true)
+ const increment = set.mock.calls[0][0]
+ expect(increment.isActive).toBeInstanceOf(SQL)
+ expect(increment.passwordAttempts).toBeInstanceOf(SQL)
+
+ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'reset')).resolves.toBe(true)
+ const reset = set.mock.calls[1][0]
+ expect(reset.passwordAttempts).toBe(0)
+ expect(reset.isActive).toBeUndefined()
+
+ await expect(usersQueries.updateAccesses(userTest.id, '127.0.0.1', 'preserve')).resolves.toBe(true)
+ const preserve = set.mock.calls[2][0]
+ expect(preserve.passwordAttempts).toBeUndefined()
+ expect(preserve.isActive).toBeUndefined()
})
it('avatars advanced: generateIsNotExists, failure branches, base64 fallback', async () => {
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index ac029fcd..1ed781e6 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -180,21 +180,10 @@ export class UsersManager {
}
async updateAccesses(user: UserModel, ip: string, success: boolean, isAuthTwoFa = false) {
- let passwordAttempts: number
- if (!isAuthTwoFa && configuration.auth.mfa.totp.enabled && user.twoFaEnabled) {
- // Do not reset password attempts if the login still requires 2FA validation
- passwordAttempts = user.passwordAttempts
- } else {
- passwordAttempts = success ? 0 : Math.min(user.passwordAttempts + 1, USER_MAX_PASSWORD_ATTEMPTS)
- }
- await this.usersQueries.updateUserOrGuest(user.id, {
- lastAccess: user.currentAccess,
- currentAccess: new Date(),
- lastIp: user.currentIp,
- currentIp: ip,
- passwordAttempts: passwordAttempts,
- isActive: user.isActive && passwordAttempts < USER_MAX_PASSWORD_ATTEMPTS
- })
+ const preservePasswordAttempts = !isAuthTwoFa && configuration.auth.mfa.totp.enabled && user.twoFaEnabled
+ if (!(await this.usersQueries.updateAccesses(user.id, ip, preservePasswordAttempts ? 'preserve' : success ? 'reset' : 'increment'))) {
+ throw new Error('Unable to update user accesses')
+ }
}
async getAvatar(userLogin: string, generate: true, generateIsNotExists?: boolean): Promise<undefined>
diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.ts
index 12c0e0b2..eba80d11 100644
--- a/backend/src/applications/users/services/users-queries.service.ts
+++ b/backend/src/applications/users/services/users-queries.service.ts
@@ -17,7 +17,7 @@ import {
} from '../../../infrastructure/database/utils'
import { GROUP_TYPE, GROUP_VISIBILITY } from '../constants/group'
import { MEMBER_TYPE } from '../constants/member'
-import { USER_GROUP_ROLE, USER_ONLINE_STATUS, USER_PERMS_SEP, USER_ROLE } from '../constants/user'
+import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ONLINE_STATUS, USER_PERMS_SEP, USER_ROLE } from '../constants/user'
import { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'
import { CreateUserDto } from '../dto/create-or-update-user.dto'
import { SearchMembersDto } from '../dto/search-members.dto'
@@ -177,6 +177,30 @@ export class UsersQueries {
}
}
+ async updateAccesses(userId: number, ip: string, passwordAttempts: 'preserve' | 'reset' | 'increment'): Promise<boolean> {
+ const set: Partial<Record<keyof User, any>> = {
+ lastAccess: users.currentAccess,
+ currentAccess: new Date(),
+ lastIp: users.currentIp,
+ currentIp: ip
+ }
+ if (passwordAttempts === 'reset') {
+ set.passwordAttempts = 0
+ } else if (passwordAttempts === 'increment') {
+ // Keep the increment and account lock in one UPDATE to avoid lost updates under concurrent authentication failures.
+ set.isActive = sql`IF(${users.passwordAttempts} >= ${USER_MAX_PASSWORD_ATTEMPTS - 1}, FALSE, ${users.isActive})`
+ set.passwordAttempts = sql`LEAST(${users.passwordAttempts} + 1, ${USER_MAX_PASSWORD_ATTEMPTS})`
+ }
+ try {
+ dbCheckAffectedRows(await this.db.update(users).set(set).where(eq(users.id, userId)), 1)
+ this.logger.verbose({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were updated` })
+ return true
+ } catch (e) {
+ this.logger.error({ tag: this.updateAccesses.name, msg: `accesses for user (${userId}) were not updated : ${e}` })
+ return false
+ }
+ }
+
async deleteGuestLink(userId: number): Promise<void> {
dbCheckAffectedRows(await this.db.delete(users).where(and(eq(users.id, userId), eq(users.role, USER_ROLE.LINK))), 1)
}
diff --git a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
index 64c4c810..ae8201df 100644
--- a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
+++ b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.spec.ts
@@ -219,6 +219,14 @@ describe(AuthProvider2FA.name, () => {
expect(usersManager.updateAccesses).toHaveBeenCalledWith(mockUser, mockRequest.ip, true, true)
})
+ it('should wait for access tracking before returning the verification result', async () => {
+ usersManager.fromUserId.mockResolvedValue(mockUser as UserModel)
+ vi.spyOn(service, 'validateTwoFactorCode').mockReturnValue({ success: true, message: '' })
+ usersManager.updateAccesses.mockRejectedValueOnce(new Error('access tracking failed'))
+
+ await expect(service.verify(verifyDto, mockRequest as FastifyAuthenticatedRequest)).rejects.toThrow('access tracking failed')
+ })
+
it('should verify recovery code successfully', async () => {
const recoveryDto: TwoFaVerifyDto = { code: 'code-1', isRecoveryCode: true }
usersManager.fromUserId.mockResolvedValue(mockUser as UserModel)
@@ -328,6 +336,13 @@ describe(AuthProvider2FA.name, () => {
)
expect(usersManager.updateAccesses).toHaveBeenCalledWith(mockUser, '127.0.0.1', false, true)
})
+
+ it('should wait for access tracking after an incorrect password', async () => {
+ usersManager.compareUserPassword.mockResolvedValue(false)
+ usersManager.updateAccesses.mockRejectedValueOnce(new Error('access tracking failed'))
+
+ await expect(service.verifyUserPassword(mockUser as UserModel, 'wrong-password', '127.0.0.1')).rejects.toThrow('access tracking failed')
+ })
})
describe('validateTwoFactorCode', () => {
diff --git a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
index 17562844..0052079e 100644
--- a/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
+++ b/backend/src/authentication/providers/two-fa/auth-provider-two-fa.service.ts
@@ -85,7 +85,7 @@ export class AuthProvider2FA {
const auth = verifyDto.isRecoveryCode
? await this.validateRecoveryCode(req.user.id, verifyDto.code, user.secrets.recoveryCodes)
: this.validateTwoFactorCode(verifyDto.code, secret)
- this.usersManager.updateAccesses(user, req.ip, auth.success, true).catch((e: Error) => this.logger.error({ tag: this.verify.name, msg: `${e}` }))
+ await this.usersManager.updateAccesses(user, req.ip, auth.success, true)
return fromLogin ? [auth, user] : auth
}
@@ -116,9 +116,7 @@ export class AuthProvider2FA {
// This function works with any authentication method, provided that
// the authentication service implements proper user password updates in the database.
if (!(await this.usersManager.compareUserPassword(user.id, password))) {
- this.usersManager
- .updateAccesses(user, ip, false, true)
- .catch((e: Error) => this.logger.error({ tag: this.verifyUserPassword.name, msg: `${e}` }))
+ await this.usersManager.updateAccesses(user, ip, false, true)
throw new HttpException('Incorrect code or password', HttpStatus.BAD_REQUEST)
}
}