Skip to content

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

fix(backend:auth): centralize local password timing mitigation

johavenb80efe045740
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 b03952e6..77604a3a 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_SCOPE } from '../../../authentication/constants/scope'
import { comparePassword } from '../../../common/functions'
import * as imageModule from '../../../common/image'
import { pngMimeType, svgMimeType } from '../../../common/image'
@@ -275,6 +276,69 @@ describe(UsersManager.name, () => {
expect(pathsSpy).toHaveBeenCalled()
})
+ it('local password validation burns time when user is missing or rejected by policy', async () => {
+ vi.mocked(comparePassword).mockResolvedValue(false)
+ usersQueriesService.from = vi.fn().mockResolvedValue(null)
+
+ await expect(usersManager.validateLocalPasswordByLogin('missing', 'pwd', '127.0.0.1')).resolves.toBeNull()
+ expect(comparePassword).toHaveBeenCalledWith('pwd', null)
+
+ await expect(usersManager.validateLocalPasswordForUser(null, 'missing', 'pwd', '127.0.0.1')).resolves.toBeNull()
+ expect(comparePassword).toHaveBeenLastCalledWith('pwd', null)
+
+ const localUser = new UserModel({ ...generateUserTest(), isActive: true, passwordAttempts: 0 }, false)
+ usersQueriesService.from = vi.fn().mockResolvedValue(localUser)
+
+ await expect(usersManager.validateLocalPasswordByLogin(localUser.login, 'pwd', '127.0.0.1', undefined, () => false)).resolves.toBeNull()
+ expect(comparePassword).toHaveBeenLastCalledWith('pwd', null)
+ })
+
+ it('scoped local password validation burns app password timing when no app password is checked', async () => {
+ vi.mocked(comparePassword).mockResolvedValue(false)
+ vi.mocked(comparePassword).mockClear()
+ usersQueriesService.from = vi.fn().mockResolvedValue(null)
+
+ await expect(usersManager.validateLocalPasswordByLogin('missing', 'pwd', '127.0.0.1', AUTH_SCOPE.WEBDAV)).resolves.toBeNull()
+ expect(comparePassword).toHaveBeenCalledTimes(2)
+ expect(comparePassword).toHaveBeenNthCalledWith(1, 'pwd', null)
+ expect(comparePassword).toHaveBeenNthCalledWith(2, 'pwd', null)
+
+ vi.mocked(comparePassword).mockClear()
+ const localUser = new UserModel({ ...generateUserTest(), role: USER_ROLE.USER, isActive: true, passwordAttempts: 0 }, false)
+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue({ appPasswords: [] })
+
+ await expect(usersManager.validateAppPassword(localUser, 'pwd', '127.0.0.1', AUTH_SCOPE.WEBDAV)).resolves.toBe(false)
+ expect(comparePassword).toHaveBeenCalledTimes(1)
+ expect(comparePassword).toHaveBeenCalledWith('pwd', null)
+
+ vi.mocked(comparePassword).mockClear()
+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue({
+ appPasswords: [{ app: AUTH_SCOPE.CLIENT, password: 'APP_HASH' }]
+ })
+
+ await expect(usersManager.validateAppPassword(localUser, 'pwd', '127.0.0.1', AUTH_SCOPE.WEBDAV)).resolves.toBe(false)
+ expect(comparePassword).toHaveBeenCalledTimes(1)
+ expect(comparePassword).toHaveBeenCalledWith('pwd', null)
+
+ vi.mocked(comparePassword).mockClear()
+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue({
+ appPasswords: [{ app: AUTH_SCOPE.WEBDAV, password: 'APP_HASH', expiration: new Date(0) }]
+ })
+
+ await expect(usersManager.validateAppPassword(localUser, 'pwd', '127.0.0.1', AUTH_SCOPE.WEBDAV)).resolves.toBe(false)
+ expect(comparePassword).toHaveBeenCalledTimes(1)
+ expect(comparePassword).toHaveBeenCalledWith('pwd', null)
+
+ vi.mocked(comparePassword).mockClear()
+ usersQueriesService.getUserSecrets = vi.fn().mockResolvedValue({
+ appPasswords: [{ app: AUTH_SCOPE.WEBDAV, password: 'APP_HASH' }]
+ })
+
+ await expect(usersManager.validateAppPassword(localUser, 'pwd', '127.0.0.1', AUTH_SCOPE.WEBDAV)).resolves.toBe(false)
+ expect(comparePassword).toHaveBeenCalledTimes(1)
+ expect(comparePassword).toHaveBeenCalledWith('pwd', 'APP_HASH')
+ })
+
it('compareUserPassword + updateLanguage + updatePassword branches', async () => {
usersQueriesService.compareUserPassword = vi.fn().mockResolvedValue(true)
await expect(usersManager.compareUserPassword(1, 'p')).resolves.toBe(true)
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index d922d863..a73ce393 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -84,6 +84,45 @@ export class UsersManager {
return user ? new UserModel(user, removePassword) : null
}
+ async validateLocalPasswordByLogin(
+ loginOrEmail: string,
+ password: string,
+ ip?: string,
+ scope?: AUTH_SCOPE,
+ canAuthenticate?: (user: UserModel) => boolean
+ ): Promise<UserModel | null> {
+ const user: UserModel = await this.findUser(loginOrEmail, false)
+ return this.validateLocalPasswordForUser(user, loginOrEmail, password, ip, scope, canAuthenticate)
+ }
+
+ async validateLocalPasswordForUser(
+ user: UserModel | null,
+ loginOrEmail: string,
+ password: string,
+ ip?: string,
+ scope?: AUTH_SCOPE,
+ canAuthenticate?: (user: UserModel) => boolean
+ ): Promise<UserModel | null> {
+ if (!user) {
+ this.logger.warn({ tag: this.validateLocalPasswordForUser.name, msg: `login or email not found for *${loginOrEmail}*` })
+ await comparePassword(password, null)
+ if (scope) {
+ // Scoped auth can also check app passwords; burn that second bcrypt path too.
+ await comparePassword(password, null)
+ }
+ return null
+ }
+ if (canAuthenticate && !canAuthenticate(user)) {
+ await comparePassword(password, null)
+ if (scope) {
+ // Match the scoped wrong-password path without revealing why local auth was rejected.
+ await comparePassword(password, null)
+ }
+ return null
+ }
+ return this.logUser(user, password, ip, scope)
+ }
+
async logUser(user: UserModel, password: string, ip: string, scope?: AUTH_SCOPE): Promise<UserModel | null> {
this.validateUserAccess(user, ip)
let authSuccess: boolean = await comparePassword(password, user.password)
@@ -285,13 +324,24 @@ export class UsersManager {
}
async validateAppPassword(user: UserModel, password: string, ip: string, scope: AUTH_SCOPE): Promise<boolean> {
- if (!scope || !user.haveRole(USER_ROLE.USER)) return false
+ if (!scope) return false
+ if (!user.haveRole(USER_ROLE.USER)) {
+ // Keep scoped auth timing close even when app passwords cannot apply to this role.
+ await comparePassword(password, null)
+ return false
+ }
const secrets = await this.usersQueries.getUserSecrets(user.id)
- if (!Array.isArray(secrets.appPasswords)) return false
+ if (!Array.isArray(secrets.appPasswords)) {
+ // No candidate app password exists, but the scoped auth path should still do bcrypt work.
+ await comparePassword(password, null)
+ return false
+ }
+ let hasComparedAppPassword = false
for (const p of secrets.appPasswords) {
if (p.app !== scope) continue
const expMs = p.expiration ? new Date(p.expiration) : null
if (p.expiration && new Date() > expMs) continue // expired
+ hasComparedAppPassword = true
if (await comparePassword(password, p.password)) {
p.lastAccess = p.currentAccess
p.currentAccess = new Date()
@@ -304,6 +354,10 @@ export class UsersManager {
return true
}
}
+ if (!hasComparedAppPassword) {
+ // All app passwords were filtered out by scope/expiration, so compare against the dummy hash.
+ await comparePassword(password, null)
+ }
return false
}
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.ts
index 076b607d..fb30e5ba 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
@@ -115,6 +115,7 @@ describe(AuthProviderLDAP.name, () => {
useValue: {
findUser: vi.fn(),
logUser: vi.fn(),
+ validateLocalPasswordForUser: vi.fn(),
updateAccesses: vi.fn().mockResolvedValue(undefined),
validateAppPassword: vi.fn(),
fromUserId: vi.fn()
@@ -157,24 +158,24 @@ describe(AuthProviderLDAP.name, () => {
const guestUser: any = { id: 1, login: 'guest1', isGuest: true, isActive: true }
usersManager.findUser.mockResolvedValue(guestUser)
const dbAuthResult: any = { ...guestUser, token: 'jwt' }
- usersManager.logUser.mockResolvedValue(dbAuthResult)
+ usersManager.validateLocalPasswordForUser.mockResolvedValue(dbAuthResult)
const res = await authProviderLDAP.validateUser('guest1', 'pass', '127.0.0.1')
expect(res).toEqual(dbAuthResult)
- expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'pass', '127.0.0.1', undefined)
+ expect(usersManager.validateLocalPasswordForUser).toHaveBeenCalledWith(guestUser, 'guest1', 'pass', '127.0.0.1', undefined)
expect(Client).not.toHaveBeenCalled()
})
it('should bypass LDAP when scope is provided', async () => {
const user = buildUser({ id: 12 })
usersManager.findUser.mockResolvedValue(user)
- usersManager.logUser.mockResolvedValue(user)
+ usersManager.validateLocalPasswordForUser.mockResolvedValue(user)
const res = await authProviderLDAP.validateUser('john', 'app-password', '10.0.0.2', 'webdav' as any)
expect(res).toBe(user)
- expect(usersManager.logUser).toHaveBeenCalledWith(user, 'app-password', '10.0.0.2', 'webdav')
+ expect(usersManager.validateLocalPasswordForUser).toHaveBeenCalledWith(user, 'john', 'app-password', '10.0.0.2', 'webdav')
expect(Client).not.toHaveBeenCalled()
})
@@ -219,7 +220,7 @@ describe(AuthProviderLDAP.name, () => {
setLdapConfig({ options: { enablePasswordAuthFallback: true } })
const existingUser: any = buildUser({ id: 2 })
usersManager.findUser.mockResolvedValue(existingUser)
- usersManager.logUser.mockResolvedValue(existingUser)
+ usersManager.validateLocalPasswordForUser.mockResolvedValue(existingUser)
const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
ldapClient.bind.mockRejectedValue({ errors: [err] })
ldapClient.unbind.mockResolvedValue(undefined)
@@ -227,7 +228,20 @@ describe(AuthProviderLDAP.name, () => {
const res = await authProviderLDAP.validateUser('john', 'pwd', '10.0.0.3')
expect(res).toBe(existingUser)
- expect(usersManager.logUser).toHaveBeenCalledWith(existingUser, 'pwd', '10.0.0.3')
+ expect(usersManager.validateLocalPasswordForUser).toHaveBeenCalledWith(existingUser, 'john', 'pwd', '10.0.0.3', undefined, expect.any(Function))
+ })
+
+ it('should burn local password timing when LDAP is unavailable and local user is missing', async () => {
+ setLdapConfig({ options: { enablePasswordAuthFallback: true } })
+ usersManager.findUser.mockResolvedValue(null)
+ usersManager.validateLocalPasswordForUser.mockResolvedValue(null)
+ const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
+ ldapClient.bind.mockRejectedValue({ errors: [err] })
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ await expect(authProviderLDAP.validateUser('john', 'pwd', '10.0.0.4')).rejects.toThrow(/authentication service error/i)
+
+ expect(usersManager.validateLocalPasswordForUser).toHaveBeenCalledWith(null, 'john', 'pwd', '10.0.0.4', undefined, expect.any(Function))
})
it('should throw SERVICE_UNAVAILABLE when LDAP is unavailable and fallback is disabled', async () => {
@@ -245,7 +259,7 @@ describe(AuthProviderLDAP.name, () => {
setLdapConfig({ options: { enablePasswordAuthFallback: false } })
const existingUser: any = buildUser({ id: 4, isAdmin: true })
usersManager.findUser.mockResolvedValue(existingUser)
- usersManager.logUser.mockResolvedValue(existingUser)
+ usersManager.validateLocalPasswordForUser.mockResolvedValue(existingUser)
const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
ldapClient.bind.mockRejectedValue({ errors: [err] })
ldapClient.unbind.mockResolvedValue(undefined)
@@ -253,7 +267,7 @@ describe(AuthProviderLDAP.name, () => {
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(res).toBe(existingUser)
- expect(usersManager.logUser).toHaveBeenCalledWith(existingUser, 'pwd', undefined)
+ expect(usersManager.validateLocalPasswordForUser).toHaveBeenCalledWith(existingUser, 'john', 'pwd', undefined, undefined, expect.any(Function))
})
it('should return null when LDAP entry lacks required fields', async () => {
diff --git a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
index f09a4ac3..dbd46433 100644
--- a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
@@ -36,11 +36,12 @@ export class AuthProviderLDAP implements AuthProvider {
async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
// Authenticate user via LDAP and sync local user state.
// Find user from his login or email
- let user: UserModel = await this.usersManager.findUser(this.dbLogin(loginOrEmail), false)
+ const 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.logUser(user, password, ip, scope)
+ 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` })
@@ -62,8 +63,11 @@ export class AuthProviderLDAP implements AuthProvider {
// Allow local password authentication for:
// - admin users (break-glass access)
// - regular users when password authentication fallback is enabled
- if (user && (user.isAdmin || (Boolean(ldapErrorMessage) && this.ldapConfig.options.enablePasswordAuthFallback))) {
- const localUser = await this.usersManager.logUser(user, password, ip)
+ const canUseLocalFallback = (candidate: UserModel): boolean =>
+ candidate.isAdmin || (Boolean(ldapErrorMessage) && this.ldapConfig.options.enablePasswordAuthFallback)
+ // Always pass through the local validator so missing or rejected fallback users take the dummy bcrypt path.
+ const localUser = await this.usersManager.validateLocalPasswordForUser(user, localLogin, password, ip, undefined, canUseLocalFallback)
+ if (user && canUseLocalFallback(user)) {
if (localUser) return localUser
}
diff --git a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
index b329155d..5d304f69 100644
--- a/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
+++ b/backend/src/authentication/providers/mysql/auth-provider-mysql.service.ts
@@ -12,20 +12,17 @@ export class AuthProviderMySQL implements AuthProvider {
constructor(private readonly usersManager: UsersManager) {}
async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
- let user: UserModel
try {
- user = await this.usersManager.findUser(loginOrEmail, false)
+ return await this.usersManager.validateLocalPasswordByLogin(loginOrEmail, password, ip, scope)
} catch (e) {
+ if (e instanceof HttpException) {
+ throw e
+ }
this.logger.error({ tag: this.validateUser.name, msg: `${e}` })
throw new HttpException(
CONNECT_ERROR_CODE.has(e.cause?.code) ? 'Authentication service error' : e.cause?.code || e.message,
HttpStatus.INTERNAL_SERVER_ERROR
)
}
- if (!user) {
- this.logger.warn({ tag: this.validateUser.name, msg: `login or email not found for *${loginOrEmail}*` })
- return null
- }
- return await this.usersManager.logUser(user, password, ip, scope)
}
}
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
index e072cbc6..1693f073 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
@@ -20,6 +20,7 @@ import * as avatarUtils from '../../../applications/users/utils/avatar'
import * as filesUtils from '../../../applications/files/utils/files'
import { DownloadFile } from '../../../applications/files/utils/download-file'
import * as imageUtils from '../../../common/image'
+import { AUTH_SCOPE } from '../../constants/scope'
import { DEFAULT_STORAGE_QUOTA_FIELD } from '../auth-providers.constants'
import { OAuthCookie } from './auth-oidc.constants'
import { AuthProviderOIDC } from './auth-provider-oidc.service'
@@ -92,6 +93,7 @@ describe(AuthProviderOIDC.name, () => {
let usersManager: {
findUser: Mock
logUser: Mock
+ validateLocalPasswordByLogin: Mock
updateAccesses: Mock
fromUserId: Mock
}
@@ -122,6 +124,7 @@ describe(AuthProviderOIDC.name, () => {
usersManager = {
findUser: vi.fn(),
logUser: vi.fn(),
+ validateLocalPasswordByLogin: vi.fn(),
updateAccesses: vi.fn().mockResolvedValue(undefined),
fromUserId: vi.fn()
}
@@ -154,28 +157,45 @@ describe(AuthProviderOIDC.name, () => {
;(service as any).oidcConfig.security.allowInsecureRequests = false
;(service as any).oidcConfig.security.allowPrivateIpAvatarDownload = false
;(service as any).oidcConfig.security.requireVerifiedEmail = false
+ ;(service as any).oidcConfig.options.enablePasswordAuth = false
;(service as any).oidcConfig.options.autoSyncAvatar = false
})
it('returns null when user is not found', async () => {
- usersManager.findUser.mockResolvedValue(null)
+ usersManager.validateLocalPasswordByLogin.mockResolvedValue(null)
const result = await service.validateUser('john', 'secret')
expect(result).toBeNull()
- expect(usersManager.findUser).toHaveBeenCalledWith('john', false)
+ expect(usersManager.validateLocalPasswordByLogin).toHaveBeenCalledWith('john', 'secret', undefined, undefined, expect.any(Function))
expect(usersManager.logUser).not.toHaveBeenCalled()
})
- it('allows local password auth for guest users', async () => {
- const guestUser = { id: 1, isGuest: true, isAdmin: false } as any
- usersManager.findUser.mockResolvedValue(guestUser)
- usersManager.logUser.mockResolvedValue(guestUser)
+ it('passes the local password policy to UsersManager', async () => {
+ const regularUser = { id: 1, isGuest: false, isAdmin: false } as any
+ const guestUser = { id: 2, isGuest: true, isAdmin: false } as any
+ const adminUser = { id: 3, isGuest: false, isAdmin: true } as any
+ usersManager.validateLocalPasswordByLogin.mockResolvedValue(regularUser)
+
+ let result = await service.validateUser('regular', 'secret')
+
+ let canAuthenticate = usersManager.validateLocalPasswordByLogin.mock.calls[0][4]
+ expect(canAuthenticate(guestUser)).toBe(true)
+ expect(canAuthenticate(adminUser)).toBe(true)
+ expect(canAuthenticate(regularUser)).toBe(false)
+ expect(result).toBe(regularUser)
+
+ await service.validateUser('regular', 'secret', undefined, AUTH_SCOPE.WEBDAV)
- const result = await service.validateUser('guest', 'secret')
+ canAuthenticate = usersManager.validateLocalPasswordByLogin.mock.calls[1][4]
+ expect(usersManager.validateLocalPasswordByLogin.mock.calls[1][3]).toBe(AUTH_SCOPE.WEBDAV)
+ expect(canAuthenticate(regularUser)).toBe(true)
+ ;(service as any).oidcConfig.options.enablePasswordAuth = true
+ result = await service.validateUser('regular', 'secret')
- expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'secret', undefined, undefined)
- expect(result).toBe(guestUser)
+ canAuthenticate = usersManager.validateLocalPasswordByLogin.mock.calls[2][4]
+ expect(canAuthenticate(regularUser)).toBe(true)
+ expect(result).toBe(regularUser)
})
it('does not allow insecure OIDC requests by default during discovery', async () => {
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
index c47ed652..35d8c630 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
@@ -62,23 +62,15 @@ export class AuthProviderOIDC implements AuthProvider {
) {}
async validateUser(login: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
- // Local password authentication path (non-OIDC)
- const user: UserModel = await this.usersManager.findUser(login, false)
-
- if (!user) {
- return null
- }
-
- if (user.isGuest || user.isAdmin || scope || this.oidcConfig.options.enablePasswordAuth) {
- // Allow local password authentication for:
- // - guest users
- // - admin users (break-glass access)
- // - application scopes (app passwords)
- // - regular users when password authentication is enabled
- return this.usersManager.logUser(user, password, ip, scope)
- }
-
- return null
+ // Non-OIDC fallback: allow local password authentication only for:
+ // - guest users
+ // - administrators (break-glass access)
+ // - scoped application access (app passwords)
+ // - regular users when password authentication is enabled
+ const canUseLocalPassword = (user: UserModel): boolean =>
+ user.isGuest || user.isAdmin || Boolean(scope) || this.oidcConfig.options.enablePasswordAuth
+
+ return this.usersManager.validateLocalPasswordByLogin(login, password, ip, scope, canUseLocalPassword)
}
async getConfig(): Promise<Configuration> {