Skip to content

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

test(backend:auth): improve coverage on auth guards and methods

johaven8ebb35c44300
diff --git a/backend/src/authentication/guards/auth-local.guard.spec.ts b/backend/src/authentication/guards/auth-local.guard.spec.ts
index f399c622..d126182c 100644
--- a/backend/src/authentication/guards/auth-local.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-local.guard.spec.ts
@@ -48,7 +48,7 @@ describe(AuthLocalGuard.name, () => {
})
it('should validate the user authentication', async () => {
- authMethod.validateUser = jest.fn().mockReturnValue(userTest)
+ authMethod.validateUser = jest.fn().mockReturnValueOnce(userTest)
context.switchToHttp().getRequest.mockReturnValue({
raw: { user: '' },
body: {
@@ -56,11 +56,13 @@ describe(AuthLocalGuard.name, () => {
password: userTest.password
}
})
- expect(await authLocalGuard.canActivate(context)).toBeDefined()
+ expect(await authLocalGuard.canActivate(context)).toBe(true)
+ expect(userTest.password).toBeUndefined()
})
it('should not validate the user authentication', async () => {
- authMethod.validateUser = jest.fn().mockReturnValue(null)
+ userTest.password = 'password'
+ authMethod.validateUser = jest.fn().mockReturnValueOnce(null)
context.switchToHttp().getRequest.mockReturnValue({
raw: { user: '' },
body: {
@@ -68,11 +70,11 @@ describe(AuthLocalGuard.name, () => {
password: userTest.password
}
})
- await expect(authLocalGuard.canActivate(context)).rejects.toThrow()
+ await expect(authLocalGuard.canActivate(context)).rejects.toThrow(/password/i)
})
it('should throw error due to malformed body', async () => {
- authMethod.validateUser = jest.fn().mockReturnValue(null)
+ authMethod.validateUser = jest.fn().mockReturnValueOnce(null)
context.switchToHttp().getRequest.mockReturnValue({
raw: { user: '' },
body: null
diff --git a/backend/src/authentication/guards/auth-token-access.guard.spec.ts b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
index d162f934..7dc5df40 100644
--- a/backend/src/authentication/guards/auth-token-access.guard.spec.ts
+++ b/backend/src/authentication/guards/auth-token-access.guard.spec.ts
@@ -170,6 +170,30 @@ describe(AuthTokenAccessGuard.name, () => {
await expect(authAccessGuard.canActivate(context)).rejects.toThrow(new RegExp(CSRF_ERROR.MISMATCH))
})
+ it('should pass with method GET and a valid access token in cookies and a mismatch CSRF', async () => {
+ context.switchToHttp().getRequest.mockReturnValue({
+ method: 'GET',
+ raw: { user: '' },
+ headers: { [authConfig.token.csrf.name]: csrfToken + '*' },
+ cookies: {
+ [authConfig.token.access.name]: accessToken
+ }
+ })
+ await expect(authAccessGuard.canActivate(context)).resolves.not.toThrow()
+ })
+
+ it('should throw an error with method POST and a valid access token in cookies and a mismatch CSRF', async () => {
+ context.switchToHttp().getRequest.mockReturnValue({
+ method: 'POST',
+ raw: { user: '' },
+ headers: { [authConfig.token.csrf.name]: csrfToken + '*' },
+ cookies: {
+ [authConfig.token.access.name]: accessToken
+ }
+ })
+ await expect(authAccessGuard.canActivate(context)).rejects.toThrow(new RegExp(CSRF_ERROR.MISMATCH))
+ })
+
it('should bypass access token when AuthTokenSkip decorator is applied to context', () => {
context = createMock<ExecutionContext>()
AuthTokenSkip()(context.getHandler())
diff --git a/backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts b/backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts
index 988ceee6..16927f77 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts
+++ b/backend/src/authentication/services/auth-methods/auth-method-database.service.spec.ts
@@ -5,6 +5,7 @@
*/
import { Test, TestingModule } from '@nestjs/testing'
+import { CONNECT_ERROR_CODE } from '../../../app.constants'
import { UserModel } from '../../../applications/users/models/user.model'
import { AdminUsersManager } from '../../../applications/users/services/admin-users-manager.service'
import { AdminUsersQueries } from '../../../applications/users/services/admin-users-queries.service'
@@ -65,11 +66,15 @@ describe(AuthMethodDatabase.name, () => {
.fn()
.mockReturnValueOnce(null)
.mockReturnValueOnce({ ...userTest, password: await hashPassword('bar') })
- .mockRejectedValueOnce({ message: 'db error', code: 'ECONNREFUSED' })
.mockRejectedValueOnce({ message: 'db error', code: 'OTHER' })
+ .mockRejectedValueOnce(
+ new Error('Authentication service error', {
+ cause: { code: Array.from(CONNECT_ERROR_CODE)[0] }
+ })
+ )
expect(await authMethodDatabase.validateUser(userTest.login, userTest.password)).toBeNull()
expect(await authMethodDatabase.validateUser(userTest.login, userTest.password)).toBeNull()
- await expect(authMethodDatabase.validateUser(userTest.login, userTest.password)).rejects.toThrow()
- await expect(authMethodDatabase.validateUser(userTest.login, userTest.password)).rejects.toThrow()
+ await expect(authMethodDatabase.validateUser(userTest.login, userTest.password)).rejects.toThrow(/db error/i)
+ await expect(authMethodDatabase.validateUser(userTest.login, userTest.password)).rejects.toThrow(/authentication service/i)
})
})
diff --git a/backend/src/authentication/services/auth-methods/auth-method-database.service.ts b/backend/src/authentication/services/auth-methods/auth-method-database.service.ts
index 89586503..990ab874 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-database.service.ts
+++ b/backend/src/authentication/services/auth-methods/auth-method-database.service.ts
@@ -22,10 +22,7 @@ export class AuthMethodDatabase implements AuthMethod {
user = await this.usersManager.findUser(loginOrEmail, false)
} catch (e) {
this.logger.error(`${this.validateUser.name} - ${e}`)
- throw new HttpException(
- CONNECT_ERROR_CODE.has(e.cause?.code) ? 'Authentication service connection error' : e.message,
- HttpStatus.INTERNAL_SERVER_ERROR
- )
+ throw new HttpException(CONNECT_ERROR_CODE.has(e.cause?.code) ? 'Authentication service error' : e.message, HttpStatus.INTERNAL_SERVER_ERROR)
}
if (!user) {
this.logger.warn(`${this.validateUser.name} - login or email not found for *${loginOrEmail}*`)
diff --git a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
index b6a259b9..9cb3f45e 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
+++ b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
@@ -5,22 +5,419 @@
*/
import { Test, TestingModule } from '@nestjs/testing'
+import { CONNECT_ERROR_CODE } from '../../../app.constants'
+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 { AuthMethodLdapService } from './auth-method-ldap.service'
+import { configuration } from '../../../configuration/config.environment'
+import { Client, InvalidCredentialsError } from 'ldapts'
+import { Mocked } from 'jest-mock'
+import * as commonFunctions from '../../../common/functions'
+
+// Mock ldapts Client to simulate LDAP behaviors
+jest.mock('ldapts', () => {
+ class InvalidCredentialsError extends Error {}
+ const mockClientInstance = {
+ bind: jest.fn(),
+ search: jest.fn(),
+ unbind: jest.fn()
+ }
+ const Client = jest.fn().mockImplementation(() => mockClientInstance)
+ return { Client, InvalidCredentialsError }
+})
+
+// --- Test helpers (DRY) ---
+// Reusable LDAP mocks
+const mockBindResolve = (ldapClient: any) => {
+ ldapClient.bind.mockResolvedValue(undefined)
+ ldapClient.unbind.mockResolvedValue(undefined)
+}
+const mockBindRejectInvalid = (ldapClient: any, InvalidCredentialsErrorCtor: any, message = 'invalid') => {
+ ldapClient.bind.mockRejectedValue(new InvalidCredentialsErrorCtor(message))
+ ldapClient.unbind.mockResolvedValue(undefined)
+}
+const mockSearchEntries = (ldapClient: any, entries: any[]) => {
+ ldapClient.search.mockResolvedValue({ searchEntries: entries })
+}
+const mockSearchReject = (ldapClient: any, err: Error) => {
+ ldapClient.search.mockRejectedValue(err)
+}
+// User factory
+const buildUser = (overrides: Partial<UserModel> = {}) =>
+ ({
+ id: 0,
+ login: 'john',
+ email: '[email protected]',
+ password: 'hashed',
+ isGuest: false,
+ isActive: true,
+ makePaths: jest.fn().mockResolvedValue(undefined),
+ ...overrides
+ }) as any
+
+// --------------------------
describe(AuthMethodLdapService.name, () => {
- let service: AuthMethodLdapService
+ let authMethodLdapService: AuthMethodLdapService
+ let usersManager: Mocked<UsersManager>
+ let adminUsersManager: Mocked<AdminUsersManager>
+ const ldapClient = {
+ bind: jest.fn(),
+ search: jest.fn(),
+ unbind: jest.fn()
+ }
+ ;(Client as Mocked<any>).mockImplementation(() => ldapClient)
+
+ // Local helpers (need access to authMethodLdapService and ldapClient in this scope)
+ const setupLdapSuccess = (entries: any[]) => {
+ mockBindResolve(ldapClient)
+ mockSearchEntries(ldapClient, entries)
+ }
+ const spyLoggerError = () => jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
- providers: [AuthMethodLdapService, { provide: UsersManager, useValue: {} }, { provide: AdminUsersManager, useValue: {} }]
+ providers: [
+ AuthMethodLdapService,
+ {
+ provide: UsersManager,
+ useValue: {
+ findUser: jest.fn(),
+ logUser: jest.fn(),
+ updateAccesses: jest.fn().mockResolvedValue(undefined)
+ }
+ },
+ {
+ provide: AdminUsersManager,
+ useValue: {
+ createUserOrGuest: jest.fn(),
+ updateUserOrGuest: jest.fn()
+ }
+ }
+ ]
}).compile()
- service = module.get<AuthMethodLdapService>(AuthMethodLdapService)
+ module.useLogger(['fatal'])
+ authMethodLdapService = module.get<AuthMethodLdapService>(AuthMethodLdapService)
+ adminUsersManager = module.get<Mocked<AdminUsersManager>>(AdminUsersManager)
+ usersManager = module.get<Mocked<UsersManager>>(UsersManager)
+ configuration.auth.ldap = { servers: ['ldap://localhost:389'], loginAttribute: 'uid', baseDN: 'ou=people,dc=example,dc=org', filter: '' }
+ })
+
+ afterEach(() => {
+ // Ensure per-test spies/mocks are reset
+ jest.restoreAllMocks()
+ jest.clearAllMocks()
})
it('should be defined', () => {
- expect(service).toBeDefined()
+ expect(authMethodLdapService).toBeDefined()
+ expect(usersManager).toBeDefined()
+ expect(adminUsersManager).toBeDefined()
+ expect(ldapClient).toBeDefined()
+ })
+
+ it('should authenticate a guest user via database and bypass LDAP', async () => {
+ // Arrange
+ 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)
+
+ const res = await authMethodLdapService.validateUser('guest1', 'pass', '127.0.0.1')
+
+ expect(res).toEqual(dbAuthResult)
+ expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'pass', '127.0.0.1')
+ expect(Client).not.toHaveBeenCalled() // client should not be constructed
+ })
+
+ it('should throw FORBIDDEN for locked account and LDAP login mismatch', async () => {
+ // Phase 1: compte verrouillé
+ usersManager.findUser.mockResolvedValue({ login: 'john', isGuest: false, isActive: false } as UserModel)
+ const loggerErrorSpy1 = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
+
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/account locked/i)
+ expect(loggerErrorSpy1).toHaveBeenCalled()
+
+ // Phase 2: mismatch entre login demandé et login retourné par LDAP
+ const existingUser: any = buildUser({ id: 8 })
+ usersManager.findUser.mockResolvedValue(existingUser)
+ const originalAttr = configuration.auth.ldap.loginAttribute
+ configuration.auth.ldap.loginAttribute = 'cn'
+ mockBindResolve(ldapClient)
+ mockSearchEntries(ldapClient, [{ uid: 'jane', cn: 'john', mail: '[email protected]' }])
+
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/account matching error/i)
+
+ // restaurer l'attribut pour ne pas impacter les autres tests
+ configuration.auth.ldap.loginAttribute = originalAttr
+ })
+
+ it('should handle invalid LDAP credentials for both existing and unknown users', async () => {
+ // Phase 1: existing user -> updateAccesses appelé avec success=false et logger.error intercepté
+ const existingUser: any = buildUser({ id: 1 })
+ usersManager.findUser.mockResolvedValue(existingUser)
+ // Make LDAP bind throw InvalidCredentialsError
+ mockBindRejectInvalid(ldapClient, InvalidCredentialsError, 'invalid credentials')
+ // Force updateAccesses to reject to hit the catch and logger.error
+ const loggerErrorSpy = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
+ usersManager.updateAccesses.mockRejectedValueOnce(new Error('updateAccesses boom'))
+
+ const res1 = await authMethodLdapService.validateUser('john', 'badpwd', '10.0.0.1')
+
+ expect(res1).toBeNull()
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '10.0.0.1', false)
+ expect(loggerErrorSpy).toHaveBeenCalled()
+
+ // Phase 2: unknown user -> aucune mise à jour des accès
+ usersManager.updateAccesses.mockClear()
+ usersManager.findUser.mockResolvedValue(null)
+ ldapClient.bind.mockRejectedValue(new InvalidCredentialsError('invalid'))
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ const res2 = await authMethodLdapService.validateUser('jane', 'badpwd')
+
+ expect(res2).toBeNull()
+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()
+ })
+
+ it('should handle LDAP new-user flow: missing fields, creation success, and multi-email selection', async () => {
+ // Phase 1: entrée LDAP incomplète -> null + log erreur, pas de création
+ usersManager.findUser.mockResolvedValue(null)
+ mockBindResolve(ldapClient)
+ // Simule une entrée avec mail manquant
+ mockSearchEntries(ldapClient, [{ uid: 'jane', cn: 'Jane Doe', mail: undefined }])
+ const loggerErrorSpy = jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)
+
+ const resA = await authMethodLdapService.validateUser('jane', 'pwd')
+
+ expect(resA).toBeNull()
+ expect(adminUsersManager.createUserOrGuest).not.toHaveBeenCalled()
+ expect(loggerErrorSpy).toHaveBeenCalled()
+
+ // Phase 2: création d'un nouvel utilisateur (succès, simple email)
+ usersManager.findUser.mockResolvedValue(null)
+ setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
+
+ const createdUser: any = { id: 2, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
+ adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
+ // Couvrir la branche de catch de succès
+ const loggerErrorSpy2 = spyLoggerError()
+ usersManager.updateAccesses.mockRejectedValueOnce(new Error('updateAccesses success flow boom'))
+
+ const resB = await authMethodLdapService.validateUser('john', 'pwd', '192.168.1.10')
+
+ expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
+ { login: 'john', email: '[email protected]', password: 'pwd', firstName: 'John', lastName: 'Doe' },
+ expect.anything() // USER_ROLE.USER
+ )
+ expect(resB).toBe(createdUser)
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(createdUser, '192.168.1.10', true)
+ expect(loggerErrorSpy2).toHaveBeenCalled()
+
+ // Phase 3: multi-emails -> garder le premier
+ usersManager.findUser.mockResolvedValue(null)
+ setupLdapSuccess([{ uid: 'multi', cn: 'Multi Mail', mail: ['[email protected]', '[email protected]'] }])
+
+ const createdUser2: any = { id: 9, login: 'multi', makePaths: jest.fn() }
+ adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser2)
+
+ const resC = await authMethodLdapService.validateUser('multi', 'pwd')
+
+ expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(expect.objectContaining({ email: '[email protected]' }), expect.anything())
+ expect(resC).toBe(createdUser2)
+ })
+
+ it('should update existing user profile when LDAP identity changed (except password assigned back)', async () => {
+ // Arrange: existing user with different profile and an old password
+ const existingUser: any = buildUser({ id: 5 })
+ usersManager.findUser.mockResolvedValue(existingUser)
+
+ // LDAP succeeds and returns different email and same uid
+ setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
+
+ // Admin manager successfully updates a user
+ adminUsersManager.updateUserOrGuest.mockResolvedValue(undefined)
+
+ // Ensure password is considered changed so the update payload includes it,
+ // which then triggers the deletion and local assignment branches after update
+ const compareSpy = jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
+
+ const res = await authMethodLdapService.validateUser('john', 'new-plain-password', '127.0.0.2')
+
+ expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
+ 5,
+ expect.objectContaining({
+ email: '[email protected]',
+ firstName: 'John',
+ lastName: 'Doe'
+ })
+ )
+ // Password should not be assigned back onto the user object (it is deleted before Object.assign)
+ expect(existingUser.password).toBe('hashed')
+ // Other fields should be updated locally
+ expect(existingUser.email).toBe('[email protected]')
+ expect(existingUser).toMatchObject({ firstName: 'John', lastName: 'Doe' })
+ // Accesses updated as success
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.2', true)
+ // Returned user is the same instance
+ expect(res).toBe(existingUser)
+
+ // Second run: password unchanged (comparePassword => true) to cover the null branch for password
+ adminUsersManager.updateUserOrGuest.mockClear()
+ usersManager.updateAccesses.mockClear()
+ // Force another non-password change so an update occurs
+ existingUser.email = '[email protected]'
+ compareSpy.mockResolvedValue(true)
+
+ const res2 = await authMethodLdapService.validateUser('john', 'same-plain-password', '127.0.0.3')
+
+ // Update should be called without password, only with changed fields
+ expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()
+ const updateArgs = adminUsersManager.updateUserOrGuest.mock.calls[0]
+ expect(updateArgs[0]).toBe(5)
+ expect(updateArgs[1]).toEqual(
+ expect.objectContaining({
+ })
+ )
+ expect(updateArgs[1]).toEqual(expect.not.objectContaining({ password: expect.anything() }))
+
+ // Password remains unchanged locally
+ expect(existingUser.password).toBe('hashed')
+ // Accesses updated as success
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.3', true)
+ // Returned user is the same instance
+ expect(res2).toBe(existingUser)
+
+ // Third run: no changes at all (identityHasChanged is empty) to cover the else branch
+ adminUsersManager.updateUserOrGuest.mockClear()
+ usersManager.updateAccesses.mockClear()
+ compareSpy.mockResolvedValue(true)
+
+ // Local user already matches LDAP identity; call again
+ const res3 = await authMethodLdapService.validateUser('john', 'same-plain-password', '127.0.0.4')
+
+ // No update should be triggered
+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
+ // Access should still be updated as success
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.4', true)
+ // Returned user is the same instance
+ expect(res3).toBe(existingUser)
+ })
+
+ it('should log failed access when LDAP search returns no entry or throws after bind', async () => {
+ // Phase 1: aucune entrée trouvée après un bind réussi -> accès échoué
+ const existingUser: any = { id: 7, login: 'ghost', isGuest: false, isActive: true }
+ usersManager.findUser.mockResolvedValue(existingUser)
+ setupLdapSuccess([])
+
+ const resA = await authMethodLdapService.validateUser('ghost', 'pwd', '10.10.0.1')
+
+ expect(resA).toBeNull()
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '10.10.0.1', false)
+
+ // Phase 2: exception lors de la recherche après un bind -> accès échoué
+ jest.clearAllMocks()
+ const existingUser2: any = { id: 10, login: 'john', isGuest: false, isActive: true }
+ usersManager.findUser.mockResolvedValue(existingUser2)
+ mockBindResolve(ldapClient)
+ mockSearchReject(ldapClient, new Error('search failed'))
+
+ const resB = await authMethodLdapService.validateUser('john', 'pwd', '1.1.1.1')
+
+ expect(resB).toBeNull()
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser2, '1.1.1.1', false)
+ })
+
+ it('should throw 500 when LDAP connection error occurs during bind', async () => {
+ // Arrange: no existing user to reach checkAuth flow
+ usersManager.findUser.mockResolvedValue(null)
+ const err1 = new Error('socket hang up')
+ const err2 = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
+ ldapClient.bind.mockRejectedValue({ errors: [err1, err2] })
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ // First scenario: recognized connection error -> throws 500
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/authentication service/i)
+
+ // Second scenario: generic error (no code, not InvalidCredentialsError) -> resolves to null and no access update
+ ldapClient.bind.mockReset()
+ ldapClient.unbind.mockReset()
+ usersManager.updateAccesses.mockClear()
+ usersManager.findUser.mockResolvedValue(null as any)
+ ldapClient.bind.mockRejectedValue(new Error('unexpected failure'))
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ const res = await authMethodLdapService.validateUser('john', 'pwd')
+ expect(res).toBeNull()
+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()
+ })
+
+ it('should log update failure and still call makePaths when updating existing user', async () => {
+ // Arrange: existing user with changed identity
+ const existingUser: any = buildUser({ id: 11, email: '[email protected]' })
+ usersManager.findUser.mockResolvedValue(existingUser)
+
+ // Ensure LDAP loginAttribute matches uid for this test (a previous test sets it to 'cn')
+ configuration.auth.ldap.loginAttribute = 'uid'
+
+ setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
+ adminUsersManager.updateUserOrGuest.mockRejectedValue(new Error('db error'))
+
+ // Force identity to be considered changed only for this test
+ jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
+ jest.spyOn(commonFunctions, 'splitFullName').mockReturnValue({ firstName: 'John', lastName: 'Doe' })
+
+ const res = await authMethodLdapService.validateUser('john', 'pwd')
+
+ expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()
+ // makePaths still invoked
+ expect(existingUser.makePaths).toHaveBeenCalled()
+ // Local fields unchanged since update failed
+ expect(existingUser.email).toBe('[email protected]')
+ expect(res).toBe(existingUser)
+ })
+
+ it('should skip non-matching LDAP entries then update user with changed password without reassigning it', async () => {
+ // Phase A: LDAP returns an entry but loginAttribute value does not match -> checkAccess returns false (covers return after loop)
+ const userA: any = { id: 20, login: 'john', isGuest: false, isActive: true }
+ usersManager.findUser.mockResolvedValue(userA)
+ configuration.auth.ldap.loginAttribute = 'uid'
+ ldapClient.bind.mockResolvedValue(undefined)
+ // Non-matching entry: uid !== requested uid
+ ldapClient.search.mockResolvedValue({ searchEntries: [{ uid: 'jane', cn: 'Jane Doe', mail: '[email protected]' }] })
+ ldapClient.unbind.mockResolvedValue(undefined)
+
+ const resA = await authMethodLdapService.validateUser('john', 'pwd', '3.3.3.3')
+ expect(resA).toBeNull()
+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(userA, '3.3.3.3', false)
+
+ // Phase B: Matching entry + password considered changed -> updateUserOrGuest called, password not reassigned locally
+ jest.clearAllMocks()
+ const userB: any = buildUser({ id: 21, email: '[email protected]' })
+ usersManager.findUser.mockResolvedValue(userB)
+ configuration.auth.ldap.loginAttribute = 'uid'
+ setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
+ adminUsersManager.updateUserOrGuest.mockResolvedValue(undefined)
+
+ // Force password to be considered changed to execute deletion + Object.assign branch
+ jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
+ jest.spyOn(commonFunctions, 'splitFullName').mockReturnValue({ firstName: 'John', lastName: 'Doe' })
+
+ const resB = await authMethodLdapService.validateUser('john', 'newpwd', '4.4.4.4')
+
+ // Line 132: updateUserOrGuest call
+ expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
+ 21,
+ expect.objectContaining({ email: '[email protected]', firstName: 'John', lastName: 'Doe' })
+ )
+ // Lines 139-142: password removed from local assign, other fields assigned
+ expect(userB.password).toBe('hashed')
+ expect(userB.email).toBe('[email protected]')
+ expect(userB).toMatchObject({ firstName: 'John', lastName: 'Doe' })
+ expect(userB.makePaths).toHaveBeenCalled()
+ expect(resB).toBe(userB)
})
})
diff --git a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts
index 4cb0aca9..a6fa5b43 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts
+++ b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.ts
@@ -33,7 +33,7 @@ export class AuthMethodLdapService implements AuthMethod {
let user = await this.usersManager.findUser(loginOrEmail, false)
if (user) {
if (user.isGuest) {
- // allow guests to be authenticated from db & check if current user is defined as active
+ // allow guests to be authenticated from db and check if the current user is defined as active
return this.usersManager.logUser(user, password, ip)
}
if (!user.isActive) {
@@ -41,7 +41,7 @@ export class AuthMethodLdapService implements AuthMethod {
throw new HttpException('Account locked', HttpStatus.FORBIDDEN)
}
}
- const entry = await this.checkAuth(loginOrEmail, password)
+ const entry: false | LdapUserEntry = await this.checkAuth(loginOrEmail, password)
if (entry === false) {
if (user) {
this.usersManager.updateAccesses(user, ip, false).catch((e: Error) => this.logger.error(`${this.validateUser.name} : ${e}`))
@@ -85,7 +85,7 @@ export class AuthMethodLdapService implements AuthMethod {
}
}
if (error && CONNECT_ERROR_CODE.has(error.code)) {
- throw new HttpException('Authentication service connection error', HttpStatus.INTERNAL_SERVER_ERROR)
+ throw new HttpException('Authentication service error', HttpStatus.INTERNAL_SERVER_ERROR)
}
return false
}
diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.json
index 303a6ebd..bc078908 100644
--- a/frontend/src/i18n/fr.json
+++ b/frontend/src/i18n/fr.json
@@ -1,7 +1,7 @@
{
"Sign-in to your account": "Connectez-vous à votre compte",
"Wrong login or password": "Identifiant ou mot de passe incorrect",
- "Authentication service connection error": "Erreur de connexion au service d’authentification",
+ "Authentication service error": "Erreur du service d’authentification",
"Account locked": "Compte verrouillé",
"Account is not allowed": "Compte non autorisé",
"Account matching error": "Erreur de correspondance de compte",