Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:auth): make user secret mutations atomic
johaven3d756002c28b
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.tsindex a8d65cef..2577955c 100755--- a/backend/src/applications/users/services/users-manager.service.spec.ts+++ b/backend/src/applications/users/services/users-manager.service.spec.ts@@ -22,6 +22,7 @@ import { MEMBER_TYPE } from '../constants/member'import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_PERMISSION, USER_ROLE } from '../constants/user'import { CreateUserDto } from '../dto/create-or-update-user.dto'import { DeleteUserDto } from '../dto/delete-user.dto'+import { UserSecrets } from '../interfaces/user-secrets.interface'import { UserModel } from '../models/user.model'import { generateUserTest } from '../utils/test'import { AdminUsersManager } from './admin-users-manager.service'@@ -81,6 +82,15 @@ describe(UsersManager.name, () => {await userTest.makePaths()}}+ const mockSecretsMutation = (initialSecrets: UserSecrets) => {+ let currentSecrets = initialSecrets+ usersQueriesService.mutateUserSecrets = vi.fn().mockImplementation(async (_userId, mutate) => {+ const mutation = mutate(currentSecrets)+ if (mutation.secrets !== undefined) currentSecrets = mutation.secrets+ return mutation.result+ })+ return () => currentSecrets+ }const notificationsManager = {sendEmailNotification: vi.fn().mockResolvedValue(undefined)@@ -342,15 +352,79 @@ describe(UsersManager.name, () => {expect(comparePassword).toHaveBeenCalledWith('pwd', 'APP_HASH')})+ it('rechecks a matched app password against the locked secrets before authenticating', async () => {+ const localUser = new UserModel({ ...generateUserTest(), role: USER_ROLE.USER, isActive: true, passwordAttempts: 0 }, false)+ const matchedPassword = {+ name: 'webdav-client',+ app: AUTH_SCOPE.WEBDAV,+ password: 'APP_HASH',+ expiration: null,+ currentAccess: new Date('2026-01-02T00:00:00.000Z'),+ lastAccess: null,+ currentIp: '127.0.0.1',+ lastIp: null,+ createdAt: new Date('2026-01-01T00:00:00.000Z')+ }+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue({ appPasswords: [matchedPassword] })+ vi.mocked(comparePassword).mockResolvedValue(true)+ const getCurrentSecrets = mockSecretsMutation({ twoFaSecret: 'two-fa', appPasswords: [matchedPassword] })++ await expect(usersManager.validateAppPassword(localUser, 'pwd', '192.0.2.10', AUTH_SCOPE.WEBDAV)).resolves.toBe(true)++ expect(getCurrentSecrets().twoFaSecret).toBe('two-fa')+ expect(getCurrentSecrets().appPasswords[0]).toEqual(+ expect.objectContaining({+ name: matchedPassword.name,+ lastAccess: matchedPassword.currentAccess,+ currentIp: '192.0.2.10',+ lastIp: matchedPassword.currentIp+ })+ )++ mockSecretsMutation({ twoFaSecret: 'two-fa', appPasswords: [] })+ await expect(usersManager.validateAppPassword(localUser, 'pwd', '192.0.2.10', AUTH_SCOPE.WEBDAV)).resolves.toBe(false)+ })++ it('updates independent secrets and consumes recovery codes from the locked state', async () => {+ const appPasswords = [{ name: 'webdav-client', app: AUTH_SCOPE.WEBDAV, password: 'HASH' }] as any+ const getCurrentSecrets = mockSecretsMutation({ twoFaSecret: 'old-secret', recoveryCodes: ['code-1', 'code-2'], appPasswords })++ await expect(usersManager.updateSecrets(userTest.id, { twoFaSecret: 'new-secret' })).resolves.toBeUndefined()+ await expect(usersManager.consumeRecoveryCode(userTest.id, 'code-1')).resolves.toBe(true)+ await expect(usersManager.consumeRecoveryCode(userTest.id, 'code-1')).resolves.toBe(false)++ expect(getCurrentSecrets()).toEqual({+ twoFaSecret: 'new-secret',+ recoveryCodes: ['code-2'],+ appPasswords+ })+ })++ it('generates an app password from the locked secrets and enforces name uniqueness there', async () => {+ const existingPassword = { name: 'existing', app: AUTH_SCOPE.CLIENT, password: 'EXISTING_HASH' } as any+ const getCurrentSecrets = mockSecretsMutation({ twoFaSecret: 'two-fa', appPasswords: [existingPassword] })++ const generated = await usersManager.generateAppPassword(userTest, { name: 'new password', app: AUTH_SCOPE.WEBDAV })++ expect(generated.name).toBe('new password')+ expect(generated.password).not.toBe('hashed-password')+ expect(getCurrentSecrets().twoFaSecret).toBe('two-fa')+ expect(getCurrentSecrets().appPasswords).toEqual([+ expect.objectContaining({ name: 'new password', password: 'hashed-password' }),+ existingPassword+ ])+ await expect(usersManager.generateAppPassword(userTest, { name: 'new password', app: AUTH_SCOPE.WEBDAV })).rejects.toThrow('Name already used')+ })+it('deletes WebDAV auth cache entries for the user when deleting a WebDAV app password', async () => {const secrets = {+ twoFaSecret: 'two-fa',appPasswords: [{ name: 'webdav-client', app: AUTH_SCOPE.WEBDAV, password: 'HASH' },{ name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }]}- usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue(secrets)- usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)+ const getCurrentSecrets = mockSecretsMutation(secrets as UserSecrets)cache.keys = vi.fn().mockResolvedValue([`${CACHE_AUTH_WEBDAV_PREFIX}-match`, `${CACHE_AUTH_WEBDAV_PREFIX}-other`, `${CACHE_AUTH_WEBDAV_PREFIX}-failed`])@@ -363,8 +437,9 @@ describe(UsersManager.name, () => {await expect(usersManager.deleteAppPassword(userTest, 'webdav-client')).resolves.toBeUndefined()- expect(usersQueriesService.updateUserOrGuest).toHaveBeenCalledWith(userTest.id, {- secrets: { appPasswords: [{ name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }] }+ expect(getCurrentSecrets()).toEqual({+ twoFaSecret: 'two-fa',+ appPasswords: [{ name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }]})expect(cache.keys).toHaveBeenCalledWith(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)expect(cache.mdel).toHaveBeenCalledWith([`${CACHE_AUTH_WEBDAV_PREFIX}-match`])@@ -374,8 +449,7 @@ describe(UsersManager.name, () => {const secrets = {appPasswords: [{ name: 'desktop-client', app: AUTH_SCOPE.CLIENT, password: 'HASH' }]}- usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue(secrets)- usersQueriesService.updateUserOrGuest = vi.fn().mockResolvedValue(true)+ mockSecretsMutation(secrets as UserSecrets)cache.keys = vi.fn()cache.mdel = vi.fn()@@ -468,6 +542,31 @@ describe(UsersManager.name, () => {expect(preserve.isActive).toBeUndefined()})+ it('should lock the user row while mutating secrets', async () => {+ const lock = vi.fn().mockResolvedValue([{ secrets: { twoFaSecret: 'old-secret', appPasswords: [{ name: 'existing' }] } }])+ const selectLimit = vi.fn().mockReturnValue({ for: lock })+ const selectWhere = vi.fn().mockReturnValue({ limit: selectLimit })+ const from = vi.fn().mockReturnValue({ where: selectWhere })+ const select = vi.fn().mockReturnValue({ from })+ const updateWhere = vi.fn().mockResolvedValue([{ affectedRows: 1 }])+ const set = vi.fn().mockReturnValue({ where: updateWhere })+ const update = vi.fn().mockReturnValue({ set })+ const tx = { select, update }+ const transaction = vi.fn().mockImplementation(async (callback) => callback(tx))+ const usersQueries = new UsersQueries({ transaction } as any, {} as Cache)++ const result = await usersQueries.mutateUserSecrets(userTest.id, (secrets) => ({+ result: 'updated',+ secrets: { ...secrets, twoFaSecret: 'new-secret' }+ }))++ expect(result).toBe('updated')+ expect(lock).toHaveBeenCalledWith('update')+ expect(set).toHaveBeenCalledWith({+ secrets: { twoFaSecret: 'new-secret', appPasswords: [{ name: 'existing' }] }+ })+ })+it('avatars advanced: generateIsNotExists, failure branches, base64 fallback', async () => {await ensurePaths()usersManager.findUser = vi.fn().mockResolvedValue({ login: userTest.login, getInitials: () => 'UT' } as unknown as UserModel)diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.tsindex 436e3839..cb9fe350 100755--- a/backend/src/applications/users/services/users-manager.service.ts+++ b/backend/src/applications/users/services/users-manager.service.ts@@ -232,13 +232,32 @@ export class UsersManager {}async updateSecrets(userId: number, secrets: UserSecrets) {- const userSecrets = await this.usersQueries.getUserSecrets(userId)- const updatedSecrets = { ...userSecrets, ...secrets }- if (!(await this.usersQueries.updateUserOrGuest(userId, { secrets: updatedSecrets }))) {+ try {+ await this.usersQueries.mutateUserSecrets(userId, (userSecrets) => ({+ result: undefined,+ secrets: { ...userSecrets, ...secrets }+ }))+ } catch (e) {+ this.logger.error({ tag: this.updateSecrets.name, msg: `Unable to update secrets for user (${userId}) : ${e}` })throw new HttpException('Unable to update secrets', HttpStatus.INTERNAL_SERVER_ERROR)}}+ consumeRecoveryCode(userId: number, encryptedCode: string): Promise<boolean> {+ // Only the transaction that still finds the code can consume it successfully.+ return this.usersQueries.mutateUserSecrets(userId, (secrets) => {+ const recoveryCodes = Array.isArray(secrets.recoveryCodes) ? secrets.recoveryCodes : []+ const codeIndex = recoveryCodes.indexOf(encryptedCode)+ if (codeIndex === -1) return { result: false }+ const updatedRecoveryCodes = [...recoveryCodes]+ updatedRecoveryCodes.splice(codeIndex, 1)+ return {+ result: true,+ secrets: { ...secrets, recoveryCodes: updatedRecoveryCodes }+ }+ })+ }+async updateAccesses(user: UserModel, ip: string, success: boolean, isAuthTwoFa = false) {const preservePasswordAttempts = success && !isAuthTwoFa && configuration.auth.mfa.totp.enabled && user.twoFaEnabledif (!(await this.usersQueries.updateAccesses(user.id, ip, preservePasswordAttempts ? 'preserve' : success ? 'reset' : 'increment'))) {@@ -288,14 +307,10 @@ export class UsersManager {}async generateAppPassword(user: UserModel, userAppPasswordDto: UserAppPasswordDto): Promise<UserAppPassword> {- const secrets = await this.usersQueries.getUserSecrets(user.id)const slugName = createLightSlug(sanitizeName(userAppPasswordDto.name))if (!slugName) throw new HttpException('Invalid name', HttpStatus.BAD_REQUEST)- if (Array.isArray(secrets.appPasswords) && secrets.appPasswords.find((p: UserAppPassword) => p.name === slugName)) {- throw new HttpException('Name already used', HttpStatus.BAD_REQUEST)- }- secrets.appPasswords = Array.isArray(secrets.appPasswords) ? secrets.appPasswords : []const clearPassword = genPassword(24)+ // Hash before acquiring the row lock: only the final read/check/write must be serialized.const appPassword: UserAppPassword = {name: slugName,app: userAppPasswordDto.app,@@ -307,8 +322,20 @@ export class UsersManager {lastIp: null,lastAccess: null}- secrets.appPasswords.unshift(appPassword)- if (!(await this.usersQueries.updateUserOrGuest(user.id, { secrets: secrets }))) {+ try {+ await this.usersQueries.mutateUserSecrets(user.id, (secrets) => {+ const appPasswords = Array.isArray(secrets.appPasswords) ? secrets.appPasswords : []+ if (appPasswords.some((p: UserAppPassword) => p.name === slugName)) {+ throw new HttpException('Name already used', HttpStatus.BAD_REQUEST)+ }+ return {+ result: undefined,+ secrets: { ...secrets, appPasswords: [appPassword, ...appPasswords] }+ }+ })+ } catch (e) {+ if (e instanceof HttpException) throw e+ this.logger.error({ tag: this.generateAppPassword.name, msg: `Unable to update app passwords for user (${user.id}) : ${e}` })throw new HttpException('Unable to update app passwords', HttpStatus.INTERNAL_SERVER_ERROR)}// return clear password only once@@ -316,16 +343,26 @@ export class UsersManager {}async deleteAppPassword(user: UserModel, passwordName: string): Promise<void> {- const secrets = await this.usersQueries.getUserSecrets(user.id)- const appPassword = Array.isArray(secrets.appPasswords) ? secrets.appPasswords.find((p: UserAppPassword) => p.name === passwordName) : undefined+ let appPassword: UserAppPassword | null+ try {+ appPassword = await this.usersQueries.mutateUserSecrets<UserAppPassword | null>(user.id, (secrets) => {+ const appPasswords = Array.isArray(secrets.appPasswords) ? secrets.appPasswords : []+ const currentAppPassword = appPasswords.find((p: UserAppPassword) => p.name === passwordName)+ if (!currentAppPassword) return { result: null }+ return {+ result: currentAppPassword,+ secrets: { ...secrets, appPasswords: appPasswords.filter((p: UserAppPassword) => p.name !== passwordName) }+ }+ })+ } catch (e) {+ this.logger.error({ tag: this.deleteAppPassword.name, msg: `Unable to delete app password for user (${user.id}) : ${e}` })+ throw new HttpException('Unable to delete app password', HttpStatus.INTERNAL_SERVER_ERROR)+ }if (!appPassword) {throw new HttpException('App password not found', HttpStatus.NOT_FOUND)}- secrets.appPasswords = secrets.appPasswords.filter((p: UserAppPassword) => p.name !== passwordName)- if (!(await this.usersQueries.updateUserOrGuest(user.id, { secrets: secrets }))) {- throw new HttpException('Unable to delete app password', HttpStatus.INTERNAL_SERVER_ERROR)- }if (appPassword.app === AUTH_SCOPE.WEBDAV) {+ // mutateUserSecrets has committed the revocation; cached Basic-auth results can now be discarded.await this.clearWebDAVAuthCache(user.id).catch((e: Error) => this.logger.error({ tag: this.clearWebDAVAuthCache.name, msg: `${e}` }))}}@@ -350,15 +387,30 @@ export class UsersManager {if (p.expiration && new Date() > expMs) continue // expiredhasComparedAppPassword = trueif (await comparePassword(password, p.password)) {- p.lastAccess = p.currentAccess- p.currentAccess = new Date()- p.lastIp = p.currentIp- p.currentIp = ip- // update accesses- this.usersQueries- .updateUserOrGuest(user.id, { secrets: secrets })- .catch((e: Error) => this.logger.error({ tag: this.validateAppPassword.name, msg: `${e}` }))- return true+ // Keep bcrypt outside the transaction, then recheck that the matched credential still exists under the row lock.+ return this.usersQueries.mutateUserSecrets(user.id, (currentSecrets) => {+ const appPasswords = Array.isArray(currentSecrets.appPasswords) ? currentSecrets.appPasswords : []+ const passwordIndex = appPasswords.findIndex(+ (currentPassword: UserAppPassword) =>+ currentPassword.name === p.name && currentPassword.app === scope && currentPassword.password === p.password+ )+ if (passwordIndex === -1) return { result: false }+ const currentPassword = appPasswords[passwordIndex]+ const currentExpiration = currentPassword.expiration ? new Date(currentPassword.expiration) : null+ if (currentExpiration && new Date() > currentExpiration) return { result: false }+ const updatedAppPasswords = [...appPasswords]+ updatedAppPasswords[passwordIndex] = {+ ...currentPassword,+ lastAccess: currentPassword.currentAccess,+ currentAccess: new Date(),+ lastIp: currentPassword.currentIp,+ currentIp: ip+ }+ return {+ result: true,+ secrets: { ...currentSecrets, appPasswords: updatedAppPasswords }+ }+ })}}if (!hasComparedAppPassword) {@@ -604,6 +656,8 @@ export class UsersManager {}private async clearWebDAVAuthCache(userId: number): Promise<void> {+ // Cache keys contain a hash of login + clear password, which cannot be rebuilt from the stored bcrypt hash.+ // Inspect cached values instead and remove every positive WebDAV authentication entry for this user.const keys = await this.cache.keys(`${CACHE_AUTH_WEBDAV_PREFIX}-*`)const keysToDelete: string[] = []for (const key of keys) {diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.tsindex 26858454..fe73ff68 100644--- a/backend/src/applications/users/services/users-queries.service.ts+++ b/backend/src/applications/users/services/users-queries.service.ts@@ -133,6 +133,26 @@ export class UsersQueries {return r.secrets || {}}+ async mutateUserSecrets<T>(userId: number, mutate: (secrets: UserSecrets) => { result: T; secrets?: UserSecrets }): Promise<T> {+ // Every secrets writer must use the latest document while holding the same row lock.+ return this.db.transaction(async (tx) => {+ const [user]: { secrets: UserSecrets }[] = await tx+ .select({ secrets: users.secrets })+ .from(users)+ .where(eq(users.id, userId))+ .limit(1)+ .for('update')+ if (!user) {+ throw new Error(`User (${userId}) not found`)+ }+ const mutation = mutate(user.secrets || {})+ if (mutation.secrets !== undefined) {+ dbCheckAffectedRows(await tx.update(users).set({ secrets: mutation.secrets }).where(eq(users.id, userId)), 1)+ }+ return mutation.result+ })+ }+selectUsers(fields: Partial<keyof User>[] = ['id', 'login', 'email'], where: SQL[]): Promise<Partial<User>[]> {const select: Record<keyof User, any> = convertToSelect(users, fields)return this.db@@ -158,7 +178,7 @@ export class UsersQueries {return userId}- async updateUserOrGuest(userId: number, set: Partial<Record<keyof User, any>>, userRole?: USER_ROLE): Promise<boolean> {+ async updateUserOrGuest(userId: number, set: Partial<Record<Exclude<keyof User, 'secrets'>, any>>, userRole?: USER_ROLE): Promise<boolean> {try {dbCheckAffectedRows(await this.dbdiff --git a/backend/src/authentication/auth.e2e-spec.ts b/backend/src/authentication/auth.e2e-spec.tsindex f0aa51bc..73f987dc 100644--- a/backend/src/authentication/auth.e2e-spec.ts+++ b/backend/src/authentication/auth.e2e-spec.ts@@ -4,17 +4,24 @@ import { NestFastifyApplication } from '@nestjs/platform-fastify'import { Type } from 'class-transformer'import { IsInt, ValidateNested } from 'class-validator'import { appBootstrap } from '../app.bootstrap'-import { USER_ROLE } from '../applications/users/constants/user'+import { genHash } from '../applications/files/utils/files'+import { USER_PERMISSION, USER_ROLE } from '../applications/users/constants/user'import { DeleteUserDto } from '../applications/users/dto/delete-user.dto'import { UserModel } from '../applications/users/models/user.model'import { AdminUsersManager } from '../applications/users/services/admin-users-manager.service'+import { UsersManager } from '../applications/users/services/users-manager.service'+import { UsersQueries } from '../applications/users/services/users-queries.service'import { generateUserTest } from '../applications/users/utils/test'+import { XML_CONTENT_TYPE } from '../applications/webdav/constants/webdav'import { convertHumanTimeToSeconds, transformAndValidate } from '../common/functions'import { currentTimeStamp, decodeUrl } from '../common/shared'+import { Cache } from '../infrastructure/cache/cache.service'import { dbCheckConnection } from '../infrastructure/database/utils'import { AuthConfig } from './auth.config'import { CSRF_ERROR, TOKEN_PATHS, TOKEN_TYPES } from './constants/auth'+import { CACHE_AUTH_WEBDAV_PREFIX } from './constants/cache'import { API_AUTH_LOGIN, API_AUTH_LOGOUT, API_AUTH_REFRESH, API_AUTH_TOKEN, API_AUTH_TOKEN_REFRESH } from './constants/routes'+import { AUTH_SCOPE } from './constants/scope'import { TokenResponseDto } from './dto/token-response.dto'import { JwtPayload } from './interfaces/jwt-payload.interface'import { TOKEN_TYPE } from './interfaces/token.interface'@@ -47,6 +54,9 @@ describe('Auth (e2e)', () => {let authConfig: AuthConfiglet jwtService: JwtServicelet adminUsersManager: AdminUsersManager+ let usersManager: UsersManager+ let usersQueries: UsersQueries+ let cache: Cachelet userTest: UserModellet refreshToken: stringlet csrfToken: string@@ -58,6 +68,9 @@ describe('Auth (e2e)', () => {authConfig = app.get<ConfigService>(ConfigService).get<AuthConfig>('auth')jwtService = app.get<JwtService>(JwtService)adminUsersManager = app.get<AdminUsersManager>(AdminUsersManager)+ usersManager = app.get<UsersManager>(UsersManager)+ usersQueries = app.get<UsersQueries>(UsersQueries)+ cache = app.get<Cache>(Cache)userTest = new UserModel(generateUserTest(false), false)})@@ -72,6 +85,9 @@ describe('Auth (e2e)', () => {expect(authConfig).toBeDefined()expect(jwtService).toBeDefined()expect(adminUsersManager).toBeDefined()+ expect(usersManager).toBeDefined()+ expect(usersQueries).toBeDefined()+ expect(cache).toBeDefined()expect(userTest).toBeDefined()})@@ -89,7 +105,7 @@ describe('Auth (e2e)', () => {})it(`POST ${API_AUTH_LOGIN} => 201`, async () => {- const userId = (await adminUsersManager.createUserOrGuest({ ...userTest }, USER_ROLE.USER)).id+ const userId = (await adminUsersManager.createUserOrGuest({ ...userTest, permissions: USER_PERMISSION.WEBDAV }, USER_ROLE.USER)).idexpect(userId).toBeDefined()userTest.id = userIdconst res = await app.inject({@@ -306,6 +322,65 @@ describe('Auth (e2e)', () => {expect(() => transformAndValidate(TokenResponseDto, res.json())).not.toThrow()})+ it('should invalidate cached WebDAV app-password authentication after revocation', async () => {+ const passwordName = 'webdav-cache-revocation'+ const appPassword = await usersManager.generateAppPassword(userTest, { name: passwordName, app: AUTH_SCOPE.WEBDAV })+ const cacheKey = webDAVAuthCacheKey(appPassword.password)++ try {+ const authenticated = await webDAVRequest(appPassword.password)+ expect(authenticated.statusCode).toBe(207)+ await vi.waitFor(async () => {+ expect(await cache.get(cacheKey)).toEqual(expect.objectContaining({ id: userTest.id }))+ })++ await usersManager.deleteAppPassword(userTest, passwordName)++ expect(await cache.get(cacheKey)).toBeUndefined()+ const revoked = await webDAVRequest(appPassword.password)+ expect(revoked.statusCode).toBe(401)+ await vi.waitFor(async () => {+ expect(await cache.get(cacheKey)).toBeNull()+ })+ } finally {+ await deleteAppPasswordIfPresent(passwordName)+ await cache.del(cacheKey)+ }+ })++ it('should not restore a revoked app password when WebDAV authentication is in flight', async () => {+ const passwordName = 'webdav-in-flight-revocation'+ const appPassword = await usersManager.generateAppPassword(userTest, { name: passwordName, app: AUTH_SCOPE.WEBDAV })+ const cacheKey = webDAVAuthCacheKey(appPassword.password)+ const getUserSecrets = usersQueries.getUserSecrets.bind(usersQueries)+ let secretsRead: () => void+ const secretsWereRead = new Promise<void>((resolve) => (secretsRead = resolve))+ let resumeValidation: () => void+ const revocationCompleted = new Promise<void>((resolve) => (resumeValidation = resolve))+ // Keep the stale read suspended until revocation commits, then let validation enter its bcrypt comparison.+ const getUserSecretsSpy = vi.spyOn(usersQueries, 'getUserSecrets').mockImplementationOnce(async (userId) => {+ const secrets = await getUserSecrets(userId)+ secretsRead()+ await revocationCompleted+ return secrets+ })++ try {+ const authentication = webDAVRequest(appPassword.password)+ await secretsWereRead+ await usersManager.deleteAppPassword(userTest, passwordName)+ resumeValidation()++ expect((await authentication).statusCode).toBe(401)+ expect(await usersManager.listAppPasswords(userTest)).not.toEqual(expect.arrayContaining([expect.objectContaining({ name: passwordName })]))+ } finally {+ resumeValidation()+ getUserSecretsSpy.mockRestore()+ await deleteAppPasswordIfPresent(passwordName)+ await cache.del(cacheKey)+ }+ })+function getCookies(setCookie: string[]): { type: TOKEN_TYPE; content: string[] }[] {const cookies: { type: TOKEN_TYPE; content: string[] }[] = []for (const c of setCookie) {@@ -350,4 +425,24 @@ describe('Auth (e2e)', () => {}}}++ function webDAVRequest(password: string) {+ const authorization = Buffer.from(`${userTest.login}:${password}`).toString('base64')+ return app.inject({+ method: 'PROPFIND',+ url: '/webdav',+ headers: { authorization: `Basic ${authorization}`, 'content-type': XML_CONTENT_TYPE, depth: '0' },+ body: '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><allprop/></propfind>'+ } as any)+ }++ function webDAVAuthCacheKey(password: string): string {+ return `${CACHE_AUTH_WEBDAV_PREFIX}-${genHash(`${userTest.login}\u0000${password}`, 'sha256')}`+ }++ async function deleteAppPasswordIfPresent(passwordName: string): Promise<void> {+ if ((await usersManager.listAppPasswords(userTest)).some(({ name }) => name === passwordName)) {+ await usersManager.deleteAppPassword(userTest, passwordName)+ }+ }})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.tsindex 6585d5b5..07e388d8 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@@ -54,7 +54,8 @@ describe(AuthProvider2FA.name, () => {validateUserAccess: vi.fn(),compareUserPassword: vi.fn(),updateAccesses: vi.fn().mockResolvedValue(undefined),- updateSecrets: vi.fn()+ updateSecrets: vi.fn(),+ consumeRecoveryCode: vi.fn()}},{@@ -238,11 +239,23 @@ describe(AuthProvider2FA.name, () => {it('should verify recovery code successfully', async () => {const recoveryDto: TwoFaVerifyDto = { code: 'code-1', isRecoveryCode: true }usersManager.fromUserId.mockResolvedValue(mockUser as UserModel)- usersManager.updateSecrets.mockResolvedValue(undefined)+ usersManager.consumeRecoveryCode.mockResolvedValue(true)await service.verify(recoveryDto, mockRequest as FastifyAuthenticatedRequest)- expect(usersManager.updateSecrets).toHaveBeenCalled()+ expect(usersManager.consumeRecoveryCode).toHaveBeenCalledWith(mockUser.id, 'encrypted-code-1')+ expect(usersManager.updateSecrets).not.toHaveBeenCalled()+ })++ it('should reject a recovery code already consumed by another request', async () => {+ const recoveryDto: TwoFaVerifyDto = { code: 'code-1', isRecoveryCode: true }+ usersManager.fromUserId.mockResolvedValue(mockUser as UserModel)+ usersManager.consumeRecoveryCode.mockResolvedValue(false)++ const result = await service.verify(recoveryDto, mockRequest as FastifyAuthenticatedRequest)++ expect(result.success).toBe(false)+ expect(result.message).toBe('Invalid code')})it('should fail when recovery codes are empty', async () => {@@ -269,7 +282,7 @@ describe(AuthProvider2FA.name, () => {it('should handle errors during recovery code validation', async () => {const recoveryDto: TwoFaVerifyDto = { code: 'code-1', isRecoveryCode: true }usersManager.fromUserId.mockResolvedValue(mockUser as UserModel)- usersManager.updateSecrets.mockRejectedValue(new Error())+ usersManager.consumeRecoveryCode.mockRejectedValue(new Error())const result = await service.verify(recoveryDto, mockRequest as FastifyAuthenticatedRequest)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.tsindex 2b1f3747..7ce60d81 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@@ -152,24 +152,23 @@ export class AuthProvider2FA {return auth}try {+ let matchedEncryptedCode: stringfor (const encCode of encryptedCodes) {const decryptedCode = this.decryptSecret(encCode)if (code === decryptedCode) {- auth.success = true- // removed used code- encryptedCodes.splice(encryptedCodes.indexOf(encCode), 1)+ matchedEncryptedCode = encCodebreak}}- if (auth.success) {- // update recovery codes- await this.usersManager.updateSecrets(userId, { recoveryCodes: encryptedCodes })+ if (matchedEncryptedCode) {+ auth.success = await this.usersManager.consumeRecoveryCode(userId, matchedEncryptedCode)+ if (!auth.success) auth.message = 'Invalid code'} else {auth.message = 'Invalid code'}} catch (e) {this.logger.error({ tag: this.validateRecoveryCode.name, msg: `${e}` })- auth.message = e.message+ auth.message = e.message || 'Invalid code'}return auth}