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): prevent account enumeration and limit password work
johaven56ea729a84ff
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.tsindex fea3e43f..d2589245 100755--- a/backend/src/applications/users/services/users-manager.service.spec.ts+++ b/backend/src/applications/users/services/users-manager.service.spec.ts@@ -7,6 +7,7 @@ import os from 'node:os'import path from 'node:path'import { Readable } from 'node:stream'import { AuthManager } from '../../../authentication/auth.service'+import { AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS } from '../../../authentication/constants/auth'import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache'import { AUTH_SCOPE } from '../../../authentication/constants/scope'import { AUTH_SESSION } from '../../../authentication/providers/auth-providers.constants'@@ -113,7 +114,7 @@ describe(UsersManager.name, () => {{ provide: AuthManager, useValue: {} },{ provide: NotificationsManager, useValue: { sendEmailNotification: vi.fn().mockResolvedValue(undefined) } },{ provide: DB_TOKEN_PROVIDER, useValue: {} },- { provide: Cache, useValue: {} }+ { provide: Cache, useValue: { consumeRateLimit: vi.fn() } }]}).compile()module.useLogger(['fatal'])@@ -126,6 +127,11 @@ describe(UsersManager.name, () => {deleteUserDto = { deleteSpace: true } satisfies DeleteUserDto})+ beforeEach(() => {+ vi.mocked(cache.consumeRateLimit).mockReset()+ vi.mocked(cache.consumeRateLimit).mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ })+afterEach(() => vi.restoreAllMocks())afterAll(async () => {@@ -269,13 +275,27 @@ describe(UsersManager.name, () => {})it('logUser branches: forbidden/locked/bad/good', async () => {+ const errSpy = vi.spyOn((usersManager as any)['logger'], 'error').mockImplementation(() => undefined as any)+ const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)+ vi.mocked(comparePassword).mockResolvedValue(false)const linkUser = new UserModel({ ...generateUserTest(), role: USER_ROLE.LINK }, false)- await expect(usersManager.logUser(linkUser, 'x', '127.0.0.1')).rejects.toThrow('Account is not allowed')+ await expect(usersManager.logUser(linkUser, 'x', '127.0.0.1')).resolves.toBeNull()+ expect(comparePassword).toHaveBeenLastCalledWith('x', linkUser.password)+ vi.mocked(comparePassword).mockResolvedValue(true)+ await expect(usersManager.logUser(linkUser, 'x', '127.0.0.1')).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ message: 'Account is not allowed'+ })const uLocked = new UserModel({ ...generateUserTest(), isActive: false, passwordAttempts: 5 }, false)- const errSpy = vi.spyOn((usersManager as any)['logger'], 'error').mockImplementation(() => undefined as any)- const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)- await expect(usersManager.logUser(uLocked, 'pwd', 'ip')).rejects.toThrow('Account locked')+ vi.mocked(comparePassword).mockResolvedValue(false)+ await expect(usersManager.logUser(uLocked, 'bad', 'ip')).resolves.toBeNull()+ expect(comparePassword).toHaveBeenLastCalledWith('bad', uLocked.password)+ vi.mocked(comparePassword).mockResolvedValue(true)+ await expect(usersManager.logUser(uLocked, 'pwd', 'ip')).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ message: 'Account locked'+ })expect(updateAccessesSpy).not.toHaveBeenCalled()vi.mocked(comparePassword).mockResolvedValue(false)const uBad = new UserModel({ ...generateUserTest(), isActive: true, passwordAttempts: 0 }, false)@@ -299,7 +319,7 @@ describe(UsersManager.name, () => {const now = new Date('2026-09-08T12:00:00.000Z').getTime()vi.spyOn(Date, 'now').mockReturnValue(now)vi.mocked(comparePassword).mockClear()- vi.mocked(comparePassword).mockResolvedValue(true)+ vi.mocked(comparePassword).mockResolvedValue(false)const resetSpy = vi.spyOn(usersQueriesService, 'resetExpiredPasswordAttempts').mockResolvedValue(true)const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)@@ -308,11 +328,14 @@ describe(UsersManager.name, () => {{ ...generateUserTest(), isActive: true, passwordAttempts: USER_MAX_PASSWORD_ATTEMPTS, currentAccess: activeLockDate },false)+ await expect(usersManager.logUser(temporarilyLockedUser, 'wrong', '127.0.0.1')).resolves.toBeNull()+ expect(comparePassword).toHaveBeenCalledWith('wrong', temporarilyLockedUser.password)+ vi.mocked(comparePassword).mockResolvedValue(true)await expect(usersManager.logUser(temporarilyLockedUser, 'password', '127.0.0.1')).rejects.toThrow('Account locked')expect(temporarilyLockedUser.currentAccess).toEqual(activeLockDate)expect(resetSpy).not.toHaveBeenCalled()expect(updateAccessesSpy).not.toHaveBeenCalled()- expect(comparePassword).not.toHaveBeenCalled()+ expect(comparePassword).toHaveBeenCalledWith('password', temporarilyLockedUser.password)const expiredLockDate = new Date(now - USER_PASSWORD_ATTEMPTS_LOCK_DURATION_MS)const expiredLockUser = new UserModel(@@ -333,7 +356,78 @@ describe(UsersManager.name, () => {false)await expect(usersManager.logUser(concurrentlyUpdatedUser, 'password', '127.0.0.1')).rejects.toThrow('Account locked')+ expect(comparePassword).toHaveBeenCalledWith('password', concurrentlyUpdatedUser.password)+ expect(updateAccessesSpy).not.toHaveBeenCalledWith(concurrentlyUpdatedUser, '127.0.0.1', true)+ })++ it('does not check app passwords or expose a locked account through scoped authentication', async () => {+ const previousTotpEnabled = configuration.auth.mfa.totp.enabled+ configuration.auth.mfa.totp.enabled = true+ try {+ const lockedUser = new UserModel(+ {+ ...generateUserTest(),+ role: USER_ROLE.USER,+ isActive: false,+ password: 'ACCOUNT_HASH',+ secrets: { twoFaSecret: 'two-fa' }+ } as any,+ false+ )+ const getSecretsSpy = vi.spyOn(usersQueriesService, 'getUserSecrets').mockResolvedValue({+ appPasswords: [{ name: 'webdav-client', app: AUTH_SCOPE.WEBDAV, password: 'APP_HASH' }]+ } as any)+ const mutateSecretsSpy = vi.spyOn(usersQueriesService, 'mutateUserSecrets')+ const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)+ const makePathsSpy = vi.spyOn(lockedUser, 'makePaths').mockResolvedValue(undefined)+ vi.mocked(comparePassword).mockImplementation(+ async (password, hash) => (password === 'primary-password' && hash === 'ACCOUNT_HASH') || (password === 'app-password' && hash === 'APP_HASH')+ )++ for (const password of ['wrong', 'app-password', 'primary-password']) {+ vi.mocked(comparePassword).mockClear()+ await expect(usersManager.logUser(lockedUser, password, '192.0.2.20', AUTH_SCOPE.WEBDAV)).resolves.toBeNull()+ expect(comparePassword).toHaveBeenCalledTimes(2)+ expect(comparePassword).toHaveBeenNthCalledWith(1, password, 'ACCOUNT_HASH')+ expect(comparePassword).toHaveBeenNthCalledWith(2, password, null)+ }++ await expect(usersManager.logUser(lockedUser, 'primary-password', '192.0.2.20', AUTH_SCOPE.CLIENT)).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ message: 'Account locked'+ })+ expect(getSecretsSpy).not.toHaveBeenCalled()+ expect(mutateSecretsSpy).not.toHaveBeenCalled()+ expect(updateAccessesSpy).not.toHaveBeenCalled()+ expect(makePathsSpy).not.toHaveBeenCalled()+ } finally {+ configuration.auth.mfa.totp.enabled = previousTotpEnabled+ }+ })++ it('limits password work for missing and locked accounts using the same identifier key', async () => {+ const lockedUser = new UserModel({ ...generateUserTest(), isActive: false }, false)+ vi.mocked(cache.consumeRateLimit).mockResolvedValue({ totalHits: 21, timeToExpire: 60, isBlocked: true, timeToBlockExpire: 60 })+ vi.mocked(comparePassword).mockClear()+ const updateAccessesSpy = vi.spyOn(usersManager, 'updateAccesses').mockResolvedValue(undefined)++ await expect(+ usersManager.validateLocalPasswordForUser(null, lockedUser.login.toUpperCase(), 'pwd', '127.0.0.1', AUTH_SCOPE.WEBDAV)+ ).rejects.toMatchObject({ status: HttpStatus.UNAUTHORIZED, message: 'Wrong login or password' })+ await expect(+ usersManager.validateLocalPasswordForUser(lockedUser, ` ${lockedUser.login} `, 'pwd', '192.0.2.11', AUTH_SCOPE.WEBDAV)+ ).rejects.toMatchObject({ status: HttpStatus.UNAUTHORIZED, message: 'Wrong login or password' })++ expect(cache.consumeRateLimit).toHaveBeenCalledTimes(2)+ expect(vi.mocked(cache.consumeRateLimit).mock.calls[0][0]).toBe(vi.mocked(cache.consumeRateLimit).mock.calls[1][0])+ expect(cache.consumeRateLimit).toHaveBeenCalledWith(+ expect.any(String),+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.ttl,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.limit,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.blockDuration+ )expect(comparePassword).not.toHaveBeenCalled()+ expect(updateAccessesSpy).not.toHaveBeenCalled()})it('local password validation burns time when user is missing or rejected by policy', async () => {diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.tsindex 782018b2..f9252b81 100755--- a/backend/src/applications/users/services/users-manager.service.ts+++ b/backend/src/applications/users/services/users-manager.service.ts@@ -8,9 +8,11 @@ import { pipeline } from 'node:stream/promises'import { CACHE_AUTH_WEBDAV_PREFIX } from '../../../authentication/constants/cache'import { AUTH_SCOPE } from '../../../authentication/constants/scope'import { LoginResponseDto } from '../../../authentication/dto/login-response.dto'+import { AuthPasswordWorkLimitException } from '../../../authentication/errors/auth-password-work-limit.exception'import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/auth-request.interface'import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface'import { AUTH_SESSION } from '../../../authentication/providers/auth-providers.constants'+import { consumePasswordWorkRateLimit } from '../../../authentication/utils/auth-rate-limit'import { comparePassword, hashPassword } from '../../../common/functions'import { convertTempImageToPng, generateAvatar, imgMimeTypePrefix, pngMimeType, svgMimeType } from '../../../common/image'import { createLightSlug, genPassword } from '../../../common/shared'@@ -123,6 +125,10 @@ export class UsersManager {scope?: AUTH_SCOPE,canAuthenticate?: (user: UserModel) => boolean): Promise<UserModel | null> {+ // Limit password work for every submitted identifier, whether or not it resolves to an account.+ const rateLimit = await consumePasswordWorkRateLimit(this.cache, loginOrEmail)+ if (rateLimit.isBlocked) throw new AuthPasswordWorkLimitException()+if (!user) {this.logger.warn({ tag: this.validateLocalPasswordForUser.name, msg: `login or email not found for *${loginOrEmail}*` })await comparePassword(password, null)@@ -144,10 +150,22 @@ export class UsersManager {}async logUser(user: UserModel, password: string, ip: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {- await this.validateUserAccess(user)+ let accessDenied: HttpException | null = null+ try {+ await this.validateUserAccess(user)+ } catch (e) {+ if (!(e instanceof HttpException) || e.getStatus() !== HttpStatus.FORBIDDEN) throw e+ accessDenied = e+ }const webDAVRequiresAppPassword = scope === AUTH_SCOPE.WEBDAV && configuration.auth.mfa.totp.enabled && user.twoFaEnabled// Keep the primary-password bcrypt path for scoped auth timing, but never accept it for 2FA WebDAV.const primaryPasswordMatches: boolean = await comparePassword(password, user.password)+ if (accessDenied) {+ // Only reveal the account state after an allowed primary password has been verified.+ if (primaryPasswordMatches && !webDAVRequiresAppPassword) throw accessDenied+ if (scope) await comparePassword(password, null)+ return null+ }let authSuccess: boolean = webDAVRequiresAppPassword ? false : primaryPasswordMatchesif (!authSuccess && scope) {authSuccess = await this.validateAppPassword(user, password, ip, scope)diff --git a/backend/src/applications/users/services/users-queries.service.spec.ts b/backend/src/applications/users/services/users-queries.service.spec.tsnew file mode 100644index 00000000..9de58657--- /dev/null+++ b/backend/src/applications/users/services/users-queries.service.spec.ts@@ -0,0 +1,23 @@+import type { Cache } from '../../../infrastructure/cache/cache.service'+import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface'+import { UsersQueries } from './users-queries.service'++describe(`${UsersQueries.name}.from`, () => {+ it('trims the identifier before searching by login or email', async () => {+ const execute = vi.fn().mockResolvedValue([])+ const query = {+ from: vi.fn().mockReturnThis(),+ leftJoin: vi.fn().mockReturnThis(),+ where: vi.fn().mockReturnThis(),+ groupBy: vi.fn().mockReturnThis(),+ limit: vi.fn().mockReturnThis(),+ prepare: vi.fn().mockReturnValue({ execute })+ }+ const db = { select: vi.fn().mockReturnValue(query) } as unknown as DBSchema+ const usersQueries = new UsersQueries(db, {} as Cache)++ await usersQueries.from(null, ' alice')++ expect(execute).toHaveBeenCalledWith({ loginOrEmail: 'alice' })+ })+})diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.tsindex b35d6a1f..d29ca3a5 100644--- a/backend/src/applications/users/services/users-queries.service.ts+++ b/backend/src/applications/users/services/users-queries.service.ts@@ -127,7 +127,7 @@ export class UsersQueries {this.fromLoginOrEmailPermissionsQuery = pQuery}}- const r = await pQuery.execute(userId ? { userId } : { loginOrEmail })+ const r = await pQuery.execute(userId ? { userId } : { loginOrEmail: loginOrEmail?.trim() })if (!r.length) return nullconst [user, groupsPermissions] = [r[0].user, r[0].groupsPermissions]// merge user and groups permissionsdiff --git a/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.ts b/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.tsindex fee0ce04..0eb325af 100644--- a/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.ts+++ b/backend/src/authentication/adapters/auth-rate-limit-storage.adapter.ts@@ -1,13 +1,12 @@import { ThrottlerStorage } from '@nestjs/throttler'import { Cache } from '../../infrastructure/cache/cache.service'import type { CacheRateLimitResult } from '../../infrastructure/cache/interfaces/cache-rate-limit.interface'-import { CACHE_AUTH_RATE_LIMIT_PREFIX } from '../constants/cache'+import { consumeRouteAuthRateLimit } from '../utils/auth-rate-limit'export class AuthRateLimitStorage implements ThrottlerStorage {constructor(private readonly cache: Cache) {}increment(key: string, ttl: number, limit: number, blockDuration: number): Promise<CacheRateLimitResult> {- // Nest already includes the route, throttler name and client tracker in its hashed key.- return this.cache.consumeRateLimit(`${CACHE_AUTH_RATE_LIMIT_PREFIX}-${key}`, ttl, limit, blockDuration)+ return consumeRouteAuthRateLimit(this.cache, key, ttl, limit, blockDuration)}}diff --git a/backend/src/authentication/auth.e2e-spec.ts b/backend/src/authentication/auth.e2e-spec.tsindex 73f987dc..9427c9e2 100644--- a/backend/src/authentication/auth.e2e-spec.ts+++ b/backend/src/authentication/auth.e2e-spec.ts@@ -179,6 +179,35 @@ describe('Auth (e2e)', () => {}})+ it(`POST ${API_AUTH_LOGIN} does not reveal an inactive account with an invalid password`, async () => {+ const invalidPassword = 'invalid-password'+ await usersQueries.updateUserOrGuest(userTest.id, { isActive: false })+ try {+ const unknown = await app.inject({+ method: 'POST',+ url: API_AUTH_LOGIN,+ body: { login: `${userTest.login}-missing`, password: invalidPassword }+ })+ const inactive = await app.inject({+ method: 'POST',+ url: API_AUTH_LOGIN,+ body: { login: userTest.login, password: invalidPassword }+ })++ expect(inactive.statusCode).toBe(401)+ expect(inactive.json()).toEqual(unknown.json())++ const verified = await app.inject({+ method: 'POST',+ url: API_AUTH_LOGIN,+ body: { login: userTest.login, password: userTest.password }+ })+ expect(verified.statusCode).toBe(403)+ } finally {+ await usersQueries.updateUserOrGuest(userTest.id, { isActive: true })+ }+ })+it(`POST ${API_AUTH_LOGOUT} => 201`, async () => {const res = await app.inject({method: 'POST',@@ -339,9 +368,7 @@ describe('Auth (e2e)', () => {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()- })+ expect(await cache.get(cacheKey)).toBeUndefined()} finally {await deleteAppPasswordIfPresent(passwordName)await cache.del(cacheKey)diff --git a/backend/src/authentication/auth.md b/backend/src/authentication/auth.mdindex 87e31baa..416292d7 100644--- a/backend/src/authentication/auth.md+++ b/backend/src/authentication/auth.md@@ -133,8 +133,9 @@ WebDAV uses HTTP Basic authentication and cannot complete the interactive Sync-iThe primary password comparison is still executed for scoped-auth timing, but a successful primary-password match is ignored for 2FA-protected WebDAV.-Revoking a WebDAV app password clears cached WebDAV Basic-auth results for that user so the revoked password cannot continue to authenticate from-cache.+Only successful WebDAV Basic-auth results are cached, for 900 seconds. Failed credentials and refusals caused by account state are never cached, so+credentials can be checked again immediately after an account is unlocked (subject to rate limits). Revoking a WebDAV app password clears cached+successful results for that user so the revoked password cannot continue to authenticate from cache.### Client registration@@ -167,6 +168,21 @@ available for break-glass recovery. See `providers/oidc/oidc.md`.Sensitive authentication and verification routes explicitly use `AuthRateLimitGuard`. The guard is selective rather than global: an unguarded routedoes not inherit this policy merely because it belongs to the authentication module.+The table covers credential and challenge routes plus notable routes without a Sync-in limiter. Every configured limit below uses a rolling 60-second+window and a 60-second block. Route/IP limits return HTTP `429`; the shared local-password work limit returns the generic HTTP `401`.++| Authentication path | HTTP route(s) | Route/IP limit | Additional limit |+|-------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------|------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------|+| Local password (MySQL, OIDC local access, LDAP guest or fallback) | `POST /api/auth/login`<br>`POST /api/auth/token` | 6 requests / 60 s per route and IP | 20 local password validations / 60 s per normalized login or email, shared across routes, scopes, and IPs. |+| Direct LDAP authentication | `POST /api/auth/login`<br>`POST /api/auth/token` | 6 / 60 s per route and IP | A valid LDAP entry skips the local-password limit. If LDAP returns no entry, the local validator runs, including its dummy path. |+| Desktop/CLI registration with a password | `POST /api/app/sync/register` | 6 / 60 s per route and IP | 20 / 60 s when the local validator runs. A valid LDAP entry skips this limit; no-entry results consume it. |+| Client-token exchange | `POST /api/app/sync/auth/:type` | 6 / 60 s per route and IP | No local-password limit; this route validates a registered client token. |+| WebDAV HTTP Basic | `PROPFIND /`<br>`PROPFIND /webdav`<br>WebDAV operations on `/webdav/*` | 60 provider lookups / 60 s per IP | 20 / 60 s when local password validation runs. Only successful credentials are cached and skip both limits; `OPTIONS` skips Basic auth. |+| TOTP verification or management | `POST /api/auth/2fa/login/verify`<br>`POST /api/auth/2fa/enable`<br>`POST /api/auth/2fa/disable`<br>`POST /api/auth/2fa/reset/user/:id` | 6 / 60 s per route and IP | No shared local-password limit, including when a TOTP management route checks the current password. |+| Public-link validation, access, and password | `GET /api/app/link/validation/:uuid`<br>`GET /api/app/link/access/:uuid`<br>`POST /api/app/link/auth/:uuid` | 6 / 60 s per route and IP | Link-password attempts have their own account lock, not the shared local-password limit. |+| Public-link download | `GET /api/app/link/download/:uuid` | 30 / 60 s per route and IP | No shared local-password limit. |+| OIDC browser redirect and callback | `GET /api/auth/oidc/login`<br>`GET /api/auth/oidc/callback` | No Sync-in route/IP limit | No local-password limit; primary authentication occurs at the identity provider. |+| Refresh or existing-session registration | `POST /api/auth/refresh`<br>`POST /api/auth/token/refresh`<br>`POST /api/app/sync/register/auth` | No `AuthRateLimitGuard` | These paths validate an existing token or session, not a submitted account password. |The default policy allows six requests for the same route and client IP in a rolling 60-second window. Every request that reaches the guard counts,regardless of its authentication outcome. The next request starts a 60-second block and returns HTTP `429` with@@ -179,6 +195,13 @@ client address therefore follows Fastify's `server.trustProxy` configuration. Liwhether the cache adapter is MySQL or Redis, so concurrent server workers observe the same counter and block period.Rate limiting and the temporary account lock cover different levels. The route limiter bounds requests from one IP before expensive authentication-work, while the account lock stops further cryptographic checks for one account after repeated failures. A distributed source can use several IPs,-so an edge or reverse-proxy limit remains a complementary deployment control. WebDAV HTTP Basic authentication uses its own rate-limit policy rather-than the default route guard described here.+work. A separate shared limiter bounds local password checks for each submitted login or email (case-insensitive) to 20 attempts in a rolling+60-second window, across IPs and authentication scopes. Dummy checks after unsuccessful LDAP authentication also count. Once exceeded, both existing+and unknown identifiers skip bcrypt and receive the same generic HTTP `401` as invalid credentials on local password paths. All local password+validation attempts count, including successful ones; cached successful WebDAV credentials do not require another validation.+The temporary account lock still prevents authentication after repeated failures, but password checks below the shared limit continue so its state+cannot be inferred from a pre-authentication response. WebDAV does not cache any failed validation, including one denied by the shared work limit.+Repeated failures therefore consume the per-IP and, for local password validation, per-identifier limits. The former negative cache only helped with+repeated identical login/password pairs; changing the submitted password bypassed it. These limits are not a global CPU budget: a distributed source+can still spread attempts across many identifiers, so an edge or reverse-proxy limit remains a complementary deployment control. WebDAV HTTP Basic+authentication uses its own per-IP rate-limit policy rather than the default route guard described here.diff --git a/backend/src/authentication/constants/auth.ts b/backend/src/authentication/constants/auth.tsindex 9cfc9807..b8c6c7ea 100644--- a/backend/src/authentication/constants/auth.ts+++ b/backend/src/authentication/constants/auth.ts@@ -21,6 +21,11 @@ export const AUTH_WEBDAV_RATE_LIMIT_OPTIONS = {ttl: 60_000,blockDuration: 60_000} as const+export const AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS = {+ limit: 20,+ ttl: 60_000,+ blockDuration: 60_000+} as constexport const AUTH_RATE_LIMIT_ERROR_MESSAGE = 'Too many requests. Please try again later.'export const TOKEN_PATHS = {diff --git a/backend/src/authentication/constants/cache.ts b/backend/src/authentication/constants/cache.tsindex 56f86a76..c542d404 100644--- a/backend/src/authentication/constants/cache.ts+++ b/backend/src/authentication/constants/cache.ts@@ -1,4 +1,4 @@-// cache key = `auth-webdav-${sha256(login + password)}` => UserModel | null+// cache key = `auth-webdav-${sha256(login + '\0' + password)}` => successful UserModel onlyexport const CACHE_AUTH_WEBDAV_PREFIX = 'auth-webdav' as constexport const CACHE_AUTH_WEBDAV_TTL = 900 as constexport const CACHE_AUTH_RATE_LIMIT_PREFIX = 'auth-rate-limit' as constdiff --git a/backend/src/authentication/errors/auth-password-work-limit.exception.ts b/backend/src/authentication/errors/auth-password-work-limit.exception.tsnew file mode 100644index 00000000..01a6de42--- /dev/null+++ b/backend/src/authentication/errors/auth-password-work-limit.exception.ts@@ -0,0 +1,7 @@+import { UnauthorizedException } from '@nestjs/common'++export class AuthPasswordWorkLimitException extends UnauthorizedException {+ constructor() {+ super('Wrong login or password')+ }+}diff --git a/backend/src/authentication/guards/auth-basic.guard.spec.ts b/backend/src/authentication/guards/auth-basic.guard.spec.tsindex 0e6da24a..85bc0ab3 100644--- a/backend/src/authentication/guards/auth-basic.guard.spec.ts+++ b/backend/src/authentication/guards/auth-basic.guard.spec.ts@@ -8,6 +8,7 @@ import { generateUserTest } from '../../applications/users/utils/test'import { WEBDAV_BASE_PATH } from '../../applications/webdav/constants/routes'import { Cache } from '../../infrastructure/cache/cache.service'import { AUTH_RATE_LIMIT_ERROR_MESSAGE } from '../constants/auth'+import { AuthPasswordWorkLimitException } from '../errors/auth-password-work-limit.exception'import { AuthProvider } from '../providers/auth-providers.models'import { AuthBasicGuard } from './auth-basic.guard'import { AuthBasicStrategy } from './auth-basic.strategy'@@ -127,38 +128,51 @@ describe(AuthBasicGuard.name, () => {expect(authProvider.validateUser).not.toHaveBeenCalled()})- it('should reject cached invalid credentials without consuming the rate limit', async () => {- cache.get = vi.fn().mockReturnValueOnce(null)- const rateLimitSpy = vi.mocked(cache.consumeRateLimit).mockClear()- authProvider.validateUser = vi.fn()- context.switchToHttp().getRequest.mockReturnValue({- ip: requestIp,- raw: { user: '' },- headers: { authorization: `Basic ${encodedAuth}` }- })- await expect(authBasicGuard.canActivate(context)).rejects.toThrow()- expect(rateLimitSpy).not.toHaveBeenCalled()- expect(authProvider.validateUser).not.toHaveBeenCalled()+ it('should revalidate a legacy negative cache entry', async () => {+ cache.get = vi.fn().mockResolvedValueOnce(null)+ cache.consumeRateLimit = vi.fn().mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ const user = new UserModel(generateUserTest(), false)+ authProvider.validateUser = vi.fn().mockResolvedValueOnce(user)++ expect(await authBasicStrategy.validate({ ip: requestIp } as FastifyRequest, user.login, 'app-password')).toBe(user)+ expect(cache.consumeRateLimit).toHaveBeenCalledOnce()+ expect(authProvider.validateUser).toHaveBeenCalledOnce()})- it('should not validate the user authentication when cache returns undefined and database return null', async () => {- cache.get = vi.fn().mockReturnValueOnce(undefined)- authProvider.validateUser = vi.fn().mockReturnValueOnce(null)+ it('should not cache a WebDAV denial and should revalidate after the account is unlocked', async () => {+ cache.get = vi.fn().mockResolvedValue(undefined)+ cache.consumeRateLimit = vi.fn().mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ const setSpy = vi.spyOn(cache, 'set').mockClear()+ const user = new UserModel(generateUserTest(), false)+ authProvider.validateUser = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce(user)+ const request = { ip: requestIp } as FastifyRequest++ expect(await authBasicStrategy.validate(request, user.login, 'app-password')).toBeNull()+ expect(setSpy).not.toHaveBeenCalled()+ expect(await authBasicStrategy.validate(request, user.login, 'app-password')).toBe(user)+ expect(cache.get).toHaveBeenCalledTimes(2)+ expect(authProvider.validateUser).toHaveBeenCalledTimes(2)+ expect(setSpy).toHaveBeenCalledOnce()+ })++ it('should log a failed cache write after successful authentication', async () => {+ cache.get = vi.fn().mockResolvedValueOnce(undefined)+ cache.consumeRateLimit = vi.fn().mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ const user = new UserModel(generateUserTest(), false)+ authProvider.validateUser = vi.fn().mockResolvedValueOnce(user)vi.spyOn(cache, 'set').mockRejectedValueOnce(new Error('cache failed'))- context.switchToHttp().getRequest.mockReturnValue({- ip: requestIp,- raw: { user: '' },- headers: { authorization: `Basic ${encodedAuth}` }- })- const loggerSpy = vi- .spyOn(authBasicStrategy['logger'], 'error') // <-- spy the SAME instance used in the class- .mockImplementation(() => undefined)- await expect(authBasicGuard.canActivate(context)).rejects.toThrow()- expect(loggerSpy).toHaveBeenCalled()- expect(loggerSpy.mock.calls[0][0]).toEqual(expect.objectContaining({ tag: 'validate', msg: expect.stringContaining('cache failed') }))+ const loggerSpy = vi.spyOn(authBasicStrategy['logger'], 'error').mockImplementation(() => undefined)++ expect(await authBasicStrategy.validate({ ip: requestIp } as FastifyRequest, user.login, 'app-password')).toBe(user)+ await vi.waitFor(() =>+ expect(loggerSpy).toHaveBeenCalledWith(expect.objectContaining({ tag: 'validate', msg: expect.stringContaining('cache failed') }))+ )})it('should not validate the user authentication', async () => {+ cache.get = vi.fn().mockResolvedValueOnce(undefined)+ cache.consumeRateLimit = vi.fn().mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ authProvider.validateUser = vi.fn().mockResolvedValueOnce(null)context.switchToHttp().getRequest.mockReturnValue({ip: requestIp,raw: { user: '' },@@ -210,4 +224,14 @@ describe(AuthBasicGuard.name, () => {)expect(authProvider.validateUser).not.toHaveBeenCalled()})++ it('should not cache credentials denied by the shared password-work limit', async () => {+ cache.get = vi.fn().mockResolvedValueOnce(undefined)+ cache.consumeRateLimit = vi.fn().mockResolvedValueOnce({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 })+ const setSpy = vi.spyOn(cache, 'set').mockClear()+ authProvider.validateUser = vi.fn().mockRejectedValueOnce(new AuthPasswordWorkLimitException())++ await expect(authBasicStrategy.validate({ ip: requestIp } as FastifyRequest, userTest.login, 'possibly-valid-password')).resolves.toBeNull()+ expect(setSpy).not.toHaveBeenCalled()+ })})diff --git a/backend/src/authentication/guards/auth-basic.strategy.ts b/backend/src/authentication/guards/auth-basic.strategy.tsindex 5a23344d..815309d1 100644--- a/backend/src/authentication/guards/auth-basic.strategy.ts+++ b/backend/src/authentication/guards/auth-basic.strategy.ts@@ -8,10 +8,12 @@ import { genHash } from '../../applications/files/utils/files'import { UserModel } from '../../applications/users/models/user.model'import { SERVER_NAME } from '../../common/shared'import { Cache } from '../../infrastructure/cache/cache.service'-import { AUTH_RATE_LIMIT_ERROR_MESSAGE, AUTH_WEBDAV_RATE_LIMIT_OPTIONS } from '../constants/auth'-import { CACHE_AUTH_RATE_LIMIT_PREFIX, CACHE_AUTH_WEBDAV_PREFIX, CACHE_AUTH_WEBDAV_TTL } from '../constants/cache'+import { AUTH_RATE_LIMIT_ERROR_MESSAGE } from '../constants/auth'+import { CACHE_AUTH_WEBDAV_PREFIX, CACHE_AUTH_WEBDAV_TTL } from '../constants/cache'import { AUTH_SCOPE } from '../constants/scope'+import { AuthPasswordWorkLimitException } from '../errors/auth-password-work-limit.exception'import { AuthProvider } from '../providers/auth-providers.models'+import { consumeWebDAVRateLimit } from '../utils/auth-rate-limit'import { HttpBasicStrategy } from './implementations/http-basic.strategy'@Injectable()@@ -29,34 +31,32 @@ export class AuthBasicStrategy extends PassportStrategy(HttpBasicStrategy, 'basithis.logger.assign({ user: loginOrEmail })const basicAuthCacheKey = `${CACHE_AUTH_WEBDAV_PREFIX}-${genHash(`${loginOrEmail}\u0000${password}`, 'sha256')}`const userFromCache: null | undefined | Partial<UserModel> = await this.cache.get(basicAuthCacheKey)- if (userFromCache === null) {- // These credentials were already rejected, so avoid another provider lookup.- return null- }- if (userFromCache !== undefined) {- // cached- // warning: plainToInstance do not use constructor to instantiate the class+ if (userFromCache) {+ // Only successful credentials are usable from cache; ignore any stale negative entry.+ // Warning: plainToInstance do not use constructor to instantiate the classreturn plainToInstance(UserModel, userFromCache)}// Every WebDAV request is authenticated: only rate limit credentials that still require an actual provider lookup.// Track by IP across all logins to also prevent password-spraying attempts.- const rateLimitTracker = genHash(req.ip, 'sha256')- const rateLimit = await this.cache.consumeRateLimit(- `${CACHE_AUTH_RATE_LIMIT_PREFIX}-webdav-${rateLimitTracker}`,- AUTH_WEBDAV_RATE_LIMIT_OPTIONS.ttl,- AUTH_WEBDAV_RATE_LIMIT_OPTIONS.limit,- AUTH_WEBDAV_RATE_LIMIT_OPTIONS.blockDuration- )+ const rateLimit = await consumeWebDAVRateLimit(this.cache, req.ip)if (rateLimit.isBlocked) {throw new ThrottlerException(AUTH_RATE_LIMIT_ERROR_MESSAGE)}- const userFromDB: UserModel = await this.authProvider.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)- if (userFromDB !== null) {- userFromDB.removePassword()+ let userFromDB: UserModel+ try {+ userFromDB = await this.authProvider.validateUser(loginOrEmail, password, req.ip, AUTH_SCOPE.WEBDAV)+ } catch (e) {+ // Keep the Basic 401 challenge when the shared work limit rejects a request.+ if (e instanceof AuthPasswordWorkLimitException) return null+ throw e}- const userToCache: Record<string, any> | null = userFromDB ? instanceToPlain(userFromDB, { excludePrefixes: ['_'] }) : null+ // Do not cache any denial: a lock can lift, and caching only other denials would create a timing oracle.+ if (userFromDB === null) return null++ userFromDB.removePassword()+ const userToCache: Record<string, any> = instanceToPlain(userFromDB, { excludePrefixes: ['_'] })this.cache.set(basicAuthCacheKey, userToCache, CACHE_AUTH_WEBDAV_TTL).catch((e: Error) => this.logger.error({ tag: this.validate.name, msg: `${e}` }))diff --git a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.tsindex d08853a2..01858b47 100644--- a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.spec.ts@@ -1,3 +1,4 @@+import { HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'import { Client, InvalidCredentialsError } from 'ldapts'import { mkdtemp, rm, writeFile } from 'node:fs/promises'@@ -179,12 +180,41 @@ describe(AuthProviderLDAP.name, () => {expect(Client).not.toHaveBeenCalled()})- it('should throw FORBIDDEN for locked account', async () => {- usersManager.findUser.mockResolvedValue({ login: 'john', isGuest: false, isActive: false } as UserModel)+ it('should not expose a locked account when LDAP credentials are invalid', async () => {+ const lockedUser = buildUser({ isActive: false })+ usersManager.findUser.mockResolvedValue(lockedUser)+ usersManager.validateLocalPasswordForUser.mockResolvedValue(null)+ mockBindRejectInvalid()++ await expect(authProviderLDAP.validateUser('john', 'wrong-password')).resolves.toBeNull()+ expect(ldapClient.bind).toHaveBeenCalled()+ expect(usersManager.validateLocalPasswordForUser).toHaveBeenCalledWith(+ lockedUser,+ 'john',+ 'wrong-password',+ undefined,+ undefined,+ expect.any(Function)+ )+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()+ })++ it('should throw FORBIDDEN for a locked account after valid LDAP credentials', async () => {+ usersManager.findUser.mockResolvedValue(buildUser({ isActive: false }))+ mockBindResolve()+ mockSearchEntries([{ uid: 'john', mail: '[email protected]' }])const loggerErrorSpy = vi.spyOn(authProviderLDAP['logger'], 'error').mockImplementation(() => undefined as any)- await expect(authProviderLDAP.validateUser('john', 'pwd')).rejects.toThrow(/account locked/i)+ await expect(authProviderLDAP.validateUser('john', 'pwd')).rejects.toMatchObject({+ status: HttpStatus.FORBIDDEN,+ message: 'Account locked'+ })+ expect(ldapClient.bind).toHaveBeenCalled()+ expect(ldapClient.search).toHaveBeenCalled()expect(loggerErrorSpy).toHaveBeenCalled()+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()})it('should reject an empty password before accessing LDAP', async () => {diff --git a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.tsindex 18c9b377..68731020 100644--- a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts@@ -42,15 +42,9 @@ export class AuthProviderLDAP implements AuthProvider {// Find user from his login or emailconst localLogin = this.dbLogin(loginOrEmail)let user: UserModel = await this.usersManager.findUser(localLogin, false)- if (user) {- if (user.isGuest || scope) {- // Allow local password authentication for guest users and application scopes (app passwords)- return this.usersManager.validateLocalPasswordForUser(user, localLogin, password, ip, scope)- }- if (!user.isActive) {- this.logger.error({ tag: this.validateUser.name, msg: `user *${user.login}* is locked` })- throw new HttpException('Account locked', HttpStatus.FORBIDDEN)- }+ if (user && (user.isGuest || scope)) {+ // Allow local password authentication for guest users and application scopes (app passwords)+ return this.usersManager.validateLocalPasswordForUser(user, localLogin, password, ip, scope)}let ldapErrorMessage: stringlet entry: false | LdapUserEntry = false@@ -82,6 +76,12 @@ export class AuthProviderLDAP implements AuthProvider {return null}+ // This LDAP branch discloses the local lock only after a valid bind; failed binds follow the fallback or generic path above.+ if (user && !user.isActive) {+ this.logger.error({ tag: this.validateUser.name, msg: `user *${user.login}* is locked` })+ throw new HttpException('Account locked', HttpStatus.FORBIDDEN)+ }+if (!entry[this.ldapConfig.attributes.login] || !entry[this.ldapConfig.attributes.email]) {this.logger.error({tag: this.validateUser.name,diff --git a/backend/src/authentication/providers/ldap/ldap.md b/backend/src/authentication/providers/ldap/ldap.mdindex 585105c4..0b3b9c90 100644--- a/backend/src/authentication/providers/ldap/ldap.md+++ b/backend/src/authentication/providers/ldap/ldap.md@@ -23,10 +23,12 @@ does not store the LDAP server, bind DN, or any LDAP token in the user record.1. The client submits a login or email and password through the normal Sync-in password flow.2. Sync-in looks for an existing local user by login or email after normalizing `DOMAIN\user` input to `user`.3. Existing guest users and existing scoped application authentications use local password or app-password validation and do not bind to LDAP.-4. Existing disabled users are rejected before LDAP authentication.-5. Sync-in builds the LDAP login from the submitted or stored local login.-6. Sync-in binds to LDAP, searches the user entry, validates the required attributes, and maps the LDAP profile to a local identity.-7. Sync-in creates a new local user when `options.autoCreateUser` is enabled, or updates the matching existing user.+4. Sync-in builds the LDAP login from the submitted or stored local login, then binds to LDAP and searches for the user entry.+5. If LDAP authentication fails, Sync-in applies the eligible local-password fallback rules, or rejects the credentials or reports an LDAP service error.+ A failed LDAP bind alone does not trigger the disabled-account `403`; a valid local fallback password can still expose that state.+6. After a successful LDAP bind and user search, Sync-in rejects an existing disabled local account before synchronizing its profile.+7. Sync-in validates the required LDAP attributes, maps the profile to a local identity, and creates a new local user when `options.autoCreateUser`+ is enabled or updates the matching existing user.8. The regular Sync-in authentication layer then issues local tokens or starts the local TOTP step when TOTP is required.LDAP is part of the local credential flow. Unlike OIDC, Sync-in TOTP can still be required after the LDAP password step for browser and bearer-token@@ -60,6 +62,17 @@ Sync-in rejects zero-length user passwords before opening an LDAP connection. Di(a non-empty bind DN with an empty password) and anonymous binds in the LDAP server policy; the application-side check is defense in depth, not areplacement for that server-side restriction.+### Rate limiting and directory protection++Sync-in limits password requests per client IP. LDAP authentication that returns a valid user entry skips the shared per-login limit. When LDAP+returns no entry (including an invalid bind or failed search), the local validator runs, including its dummy path when no fallback is eligible, and+consumes that limit. An LDAP bind itself does not increment Sync-in's local password-attempt counter; an eligible local fallback can do so.+See [Authentication rate limiting](../../auth.md#authentication-rate-limiting) for the limits by route and authentication method.++The LDAP directory may apply its own failed-bind, lockout, or throttling policy, but that depends on the directory and its configuration; Sync-in does+not configure or verify it. Operators should review the directory policy and monitor failed binds. Where distributed attempts are a concern, an edge+limit complements both the directory policy and Sync-in's per-IP limits. Account lockout policies also need to account for deliberate lockout attacks.+## User searchUser searches run under `baseDN` with subtree scope. Sync-in asks LDAP for the known login attributes, common profile attributes, the configured emaildiff --git a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.tsindex 2f87a284..594000ff 100644--- a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts+++ b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.spec.ts@@ -28,7 +28,10 @@ describe(AuthProviderMySQL.name, () => {{ provide: AdminUsersManager, useValue: {} },{ provide: AuthManager, useValue: {} },{ provide: DB_TOKEN_PROVIDER, useValue: {} },- { provide: Cache, useValue: {} },+ {+ provide: Cache,+ useValue: { consumeRateLimit: vi.fn().mockResolvedValue({ totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 }) }+ },{ provide: NotificationsManager, useValue: {} }]}).compile()diff --git a/backend/src/authentication/utils/auth-rate-limit.spec.ts b/backend/src/authentication/utils/auth-rate-limit.spec.tsnew file mode 100644index 00000000..41a57871--- /dev/null+++ b/backend/src/authentication/utils/auth-rate-limit.spec.ts@@ -0,0 +1,49 @@+import type { Cache } from '../../infrastructure/cache/cache.service'+import { AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS, AUTH_WEBDAV_RATE_LIMIT_OPTIONS } from '../constants/auth'+import { consumePasswordWorkRateLimit, consumeRouteAuthRateLimit, consumeWebDAVRateLimit } from './auth-rate-limit'++describe('Authentication rate-limit helpers', () => {+ const rateLimitResult = { totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 }++ it('keeps Nest route trackers in their own cache namespace', async () => {+ const consumeRateLimit = vi.fn().mockResolvedValue(rateLimitResult)+ const cache = { consumeRateLimit } as unknown as Cache++ await consumeRouteAuthRateLimit(cache, 'nest-tracker', 1_000, 6, 2_000)++ expect(consumeRateLimit).toHaveBeenCalledWith('auth-rate-limit-nest-tracker', 1_000, 6, 2_000)+ })++ it('hashes the WebDAV client IP and applies the WebDAV policy', async () => {+ const consumeRateLimit = vi.fn().mockResolvedValue(rateLimitResult)+ const cache = { consumeRateLimit } as unknown as Cache++ await consumeWebDAVRateLimit(cache, '192.0.2.1')++ expect(consumeRateLimit).toHaveBeenCalledWith(+ expect.stringMatching(/^auth-rate-limit-webdav-[a-f0-9]{64}$/),+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.ttl,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.limit,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.blockDuration+ )+ })++ it('uses one password-work key for equivalent submitted identifiers', async () => {+ const consumeRateLimit = vi.fn().mockResolvedValue(rateLimitResult)+ const cache = { consumeRateLimit } as unknown as Cache++ await consumePasswordWorkRateLimit(cache, ' [email protected] ')+ await consumePasswordWorkRateLimit(cache, '[email protected]')+ await consumePasswordWorkRateLimit(cache, 'cafe')+ await consumePasswordWorkRateLimit(cache, 'café')++ expect(consumeRateLimit.mock.calls[0][0]).toBe(consumeRateLimit.mock.calls[1][0])+ expect(consumeRateLimit.mock.calls[2][0]).toBe(consumeRateLimit.mock.calls[3][0])+ expect(consumeRateLimit).toHaveBeenCalledWith(+ expect.stringMatching(/^auth-rate-limit-password-[a-f0-9]{64}$/),+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.ttl,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.limit,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.blockDuration+ )+ })+})diff --git a/backend/src/authentication/utils/auth-rate-limit.ts b/backend/src/authentication/utils/auth-rate-limit.tsnew file mode 100644index 00000000..6c3d9fc7--- /dev/null+++ b/backend/src/authentication/utils/auth-rate-limit.ts@@ -0,0 +1,40 @@+import crypto from 'node:crypto'+import { createLightSlug } from '../../common/shared'+import type { Cache } from '../../infrastructure/cache/cache.service'+import type { CacheRateLimitResult } from '../../infrastructure/cache/interfaces/cache-rate-limit.interface'+import { AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS, AUTH_WEBDAV_RATE_LIMIT_OPTIONS } from '../constants/auth'+import { CACHE_AUTH_RATE_LIMIT_PREFIX } from '../constants/cache'++function hashTracker(value: string): string {+ return crypto.createHash('sha256').update(value).digest('hex')+}++export function consumeRouteAuthRateLimit(+ cache: Cache,+ key: string,+ ttl: number,+ limit: number,+ blockDuration: number+): Promise<CacheRateLimitResult> {+ // Nest's key already contains the route, throttler name and client IP.+ return cache.consumeRateLimit(`${CACHE_AUTH_RATE_LIMIT_PREFIX}-${key}`, ttl, limit, blockDuration)+}++export function consumeWebDAVRateLimit(cache: Cache, ip: string): Promise<CacheRateLimitResult> {+ return cache.consumeRateLimit(+ `${CACHE_AUTH_RATE_LIMIT_PREFIX}-webdav-${hashTracker(ip)}`,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.ttl,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.limit,+ AUTH_WEBDAV_RATE_LIMIT_OPTIONS.blockDuration+ )+}++export function consumePasswordWorkRateLimit(cache: Cache, loginOrEmail: string): Promise<CacheRateLimitResult> {+ // This key must depend on the submitted identifier, never on whether a user was found.+ return cache.consumeRateLimit(+ `${CACHE_AUTH_RATE_LIMIT_PREFIX}-password-${hashTracker(createLightSlug(loginOrEmail))}`,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.ttl,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.limit,+ AUTH_PASSWORD_WORK_RATE_LIMIT_OPTIONS.blockDuration+ )+}