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): improve AD/LDAP authentication handling and normalization
johavendb1a9e3d4a02
diff --git a/backend/src/authentication/auth.config.ts b/backend/src/authentication/auth.config.tsindex f850838f..ac2d33e3 100644--- a/backend/src/authentication/auth.config.ts+++ b/backend/src/authentication/auth.config.ts@@ -10,6 +10,7 @@ import {IsArray,IsBoolean,IsDefined,+ IsEnum,IsIn,IsNotEmpty,IsNotEmptyObject,@@ -21,6 +22,7 @@ import {} from 'class-validator'import { SERVER_NAME } from '../app.constants'import { ACCESS_KEY, CSRF_KEY, REFRESH_KEY, WS_KEY } from './constants/auth'+import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './constants/auth-ldap'export class AuthMfaTotpConfig {@IsBoolean()@@ -112,13 +114,14 @@ export class AuthTokenConfig {export class AuthMethodLdapAttributesConfig {@IsOptional()@IsString()- @Transform(({ value }) => value || 'uid')- login? = 'uid'+ @Transform(({ value }) => value || LDAP_LOGIN_ATTR.UID)+ @IsEnum(LDAP_LOGIN_ATTR)+ login: LDAP_LOGIN_ATTR = LDAP_LOGIN_ATTR.UID@IsOptional()@IsString()- @Transform(({ value }) => value || 'mail')- email? = 'mail'+ @Transform(({ value }) => value || LDAP_COMMON_ATTR.MAIL)+ email: string = LDAP_COMMON_ATTR.MAIL}export class AuthMethodLdapConfig {diff --git a/backend/src/authentication/constants/auth-ldap.ts b/backend/src/authentication/constants/auth-ldap.tsnew file mode 100644index 00000000..eccbd7c3--- /dev/null+++ b/backend/src/authentication/constants/auth-ldap.ts@@ -0,0 +1,21 @@+/*+ * Copyright (C) 2012-2025 Johan Legrand <[email protected]>+ * This file is part of Sync-in | The open source file sync and share solution+ * See the LICENSE file for licensing details+ */++export enum LDAP_LOGIN_ATTR {+ UID = 'uid',+ SAM = 'sAMAccountName',+ UPN = 'userPrincipalName'+}++export const LDAP_COMMON_ATTR = {+ MAIL: 'mail',+ GIVEN_NAME: 'givenName',+ SN: 'sn',+ CN: 'cn',+ DISPLAY_NAME: 'displayName'+} as const++export const ALL_LDAP_ATTRIBUTES = [...Object.values(LDAP_LOGIN_ATTR), ...Object.values(LDAP_COMMON_ATTR)]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.tsindex 5540810c..6d12afd3 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@@ -13,18 +13,20 @@ import { AdminUsersManager } from '../../../applications/users/services/admin-usimport { UsersManager } from '../../../applications/users/services/users-manager.service'import * as commonFunctions from '../../../common/functions'import { configuration } from '../../../configuration/config.environment'+import { LDAP_LOGIN_ATTR } from '../../constants/auth-ldap'import { AuthMethodLdapService } from './auth-method-ldap.service'// Mock ldapts Client to simulate LDAP behaviorsjest.mock('ldapts', () => {- class InvalidCredentialsError extends Error {}+ const actual = jest.requireActual('ldapts')const mockClientInstance = {bind: jest.fn(),search: jest.fn(),unbind: jest.fn()}const Client = jest.fn().mockImplementation(() => mockClientInstance)- return { Client, InvalidCredentialsError }+ // Conserver tous les autres exports réels (dont EqualityFilter, AndFilter, InvalidCredentialsError, etc.)+ return { ...actual, Client }})// --- Test helpers (DRY) ---@@ -53,6 +55,7 @@ const buildUser = (overrides: Partial<UserModel> = {}) =>isGuest: false,isActive: true,makePaths: jest.fn().mockResolvedValue(undefined),+ setFullName: jest.fn(), // needed when firstName/lastName change...overrides}) as any@@ -77,6 +80,13 @@ describe(AuthMethodLdapService.name, () => {const spyLoggerError = () => jest.spyOn(authMethodLdapService['logger'], 'error').mockImplementation(() => undefined as any)beforeAll(async () => {+ configuration.auth.ldap = {+ servers: ['ldap://localhost:389'],+ attributes: { login: LDAP_LOGIN_ATTR.UID, email: 'mail' },+ baseDN: 'ou=people,dc=example,dc=org',+ filter: ''+ }+const module: TestingModule = await Test.createTestingModule({providers: [AuthMethodLdapService,@@ -85,7 +95,9 @@ describe(AuthMethodLdapService.name, () => {useValue: {findUser: jest.fn(),logUser: jest.fn(),- updateAccesses: jest.fn().mockResolvedValue(undefined)+ updateAccesses: jest.fn().mockResolvedValue(undefined),+ validateAppPassword: jest.fn(),+ fromUserId: jest.fn()}},{@@ -102,12 +114,6 @@ describe(AuthMethodLdapService.name, () => {authMethodLdapService = module.get<AuthMethodLdapService>(AuthMethodLdapService)adminUsersManager = module.get<Mocked<AdminUsersManager>>(AdminUsersManager)usersManager = module.get<Mocked<UsersManager>>(UsersManager)- configuration.auth.ldap = {- servers: ['ldap://localhost:389'],- attributes: { login: 'uid', email: 'mail' },- baseDN: 'ou=people,dc=example,dc=org',- filter: ''- }})it('should be defined', () => {@@ -123,29 +129,25 @@ describe(AuthMethodLdapService.name, () => {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 () => {+ it('should throw FORBIDDEN for locked account and resolve null for LDAP login mismatch', async () => {// Phase 1: locked accountusersManager.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 between requested login and LDAP returned login+ // Phase 2: mismatch between requested login and LDAP returned login -> service renvoie nullconst existingUser: any = buildUser({ id: 8 })usersManager.findUser.mockResolvedValue(existingUser)mockBindResolve(ldapClient)mockSearchEntries(ldapClient, [{ uid: 'jane', cn: 'john', mail: '[email protected]' }])-- await expect(authMethodLdapService.validateUser('john', 'pwd')).resolves.toEqual(null)+ await expect(authMethodLdapService.validateUser('john', 'pwd')).rejects.toThrow(/account matching error/i)})it('should handle invalid LDAP credentials for both existing and unknown users', async () => {@@ -157,9 +159,7 @@ describe(AuthMethodLdapService.name, () => {// Force updateAccesses to reject to hit the catch and logger.errorconst 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()@@ -169,9 +169,7 @@ describe(AuthMethodLdapService.name, () => {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()})@@ -183,25 +181,25 @@ describe(AuthMethodLdapService.name, () => {// Simulate an entry with missing mailmockSearchEntries(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: create a new user (success, single email)+ // Stub directement checkAuth pour retourner une entrée LDAP valide+ const checkAuthSpy = jest.spyOn<any, any>(authMethodLdapService as any, 'checkAuth')+ checkAuthSpy.mockResolvedValueOnce({ uid: 'john', cn: 'John Doe', mail: '[email protected]' } as any)+ adminUsersManager.createUserOrGuest.mockClear()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)+ // If the service reloads the user via fromUserId after creation+ usersManager.fromUserId.mockResolvedValue(createdUser)// Cover the success-flow catch branchconst 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@@ -209,16 +207,14 @@ describe(AuthMethodLdapService.name, () => {expect(resB).toBe(createdUser)expect(usersManager.updateAccesses).toHaveBeenCalledWith(createdUser, '192.168.1.10', true)expect(loggerErrorSpy2).toHaveBeenCalled()-// Phase 3: multiple emails -> keep the first+ adminUsersManager.createUserOrGuest.mockClear()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)-+ usersManager.fromUserId.mockResolvedValue(createdUser2)const resC = await authMethodLdapService.validateUser('multi', 'pwd')-expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(expect.objectContaining({ email: '[email protected]' }), expect.anything())expect(resC).toBe(createdUser2)})@@ -227,19 +223,14 @@ describe(AuthMethodLdapService.name, () => {// Arrange: existing user with different profile and an old passwordconst existingUser: any = buildUser({ id: 5 })usersManager.findUser.mockResolvedValue(existingUser)-// LDAP succeeds and returns different email and same uidsetupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])-// Admin manager successfully updates a useradminUsersManager.updateUserOrGuest.mockResolvedValue(undefined)-// Ensure password is considered changed so the update payload includes it,// which then triggers the deletion and local assignment branches after updateconst 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({@@ -264,9 +255,7 @@ describe(AuthMethodLdapService.name, () => {// Force another non-password change so an update occursexistingUser.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 fieldsexpect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()const updateArgs = adminUsersManager.updateUserOrGuest.mock.calls[0]@@ -277,22 +266,18 @@ describe(AuthMethodLdapService.name, () => {}))expect(updateArgs[1]).toEqual(expect.not.objectContaining({ password: expect.anything() }))-// Password remains unchanged locallyexpect(existingUser.password).toBe('hashed')// Accesses updated as successexpect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.3', true)// Returned user is the same instanceexpect(res2).toBe(existingUser)-// Third run: no changes at all (identityHasChanged is empty) to cover the else branchadminUsersManager.updateUserOrGuest.mockClear()usersManager.updateAccesses.mockClear()compareSpy.mockResolvedValue(true)-// Local user already matches LDAP identity; call againconst res3 = await authMethodLdapService.validateUser('john', 'same-plain-password', '127.0.0.4')-// No update should be triggeredexpect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()// Access should still be updated as success@@ -306,9 +291,7 @@ describe(AuthMethodLdapService.name, () => {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)@@ -318,13 +301,24 @@ describe(AuthMethodLdapService.name, () => {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 allow app password when LDAP fails and scope is provided', async () => {+ const existingUser: any = buildUser({ id: 42 })+ usersManager.findUser.mockResolvedValue(existingUser)+ // LDAP invalid credentials+ mockBindRejectInvalid(ldapClient, InvalidCredentialsError, 'invalid credentials')+ // App password success+ usersManager.validateAppPassword.mockResolvedValue(true)+ const res = await authMethodLdapService.validateUser('john', 'app-password', '10.0.0.2', 'webdav' as any)+ expect(res).toBe(existingUser)+ expect(usersManager.validateAppPassword).toHaveBeenCalledWith(existingUser, 'app-password', '10.0.0.2', 'webdav')+ expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '10.0.0.2', true)+ })+it('should throw 500 when LDAP connection error occurs during bind', async () => {// Arrange: no existing user to reach checkAuth flowusersManager.findUser.mockResolvedValue(null)@@ -349,26 +343,18 @@ describe(AuthMethodLdapService.name, () => {expect(usersManager.updateAccesses).not.toHaveBeenCalled()})- it('should log update failure and still call makePaths when updating existing user', async () => {+ it('should log update failure when updating existing user', async () => {// Arrange: existing user with changed identityconst 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.attributes.login = '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 testjest.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 failedexpect(existingUser.email).toBe('[email protected]')expect(res).toBe(existingUser)@@ -378,28 +364,18 @@ describe(AuthMethodLdapService.name, () => {// 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.attributes.login = '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 locallyjest.clearAllMocks()const userB: any = buildUser({ id: 21, email: '[email protected]' })usersManager.findUser.mockResolvedValue(userB)- configuration.auth.ldap.attributes.login = '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 branchjest.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@@ -407,11 +383,11 @@ describe(AuthMethodLdapService.name, () => {21,expect.objectContaining({ email: '[email protected]', firstName: 'John', lastName: 'Doe' }))+// Lines 139-142: password removed from local assign, other fields assignedexpect(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.tsindex 093214b8..439c4dc9 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@@ -5,7 +5,7 @@*/import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'-import { Client, ClientOptions, Entry, InvalidCredentialsError } from 'ldapts'+import { AndFilter, Client, ClientOptions, Entry, EqualityFilter, InvalidCredentialsError } from 'ldapts'import { CONNECT_ERROR_CODE } from '../../../app.constants'import { USER_ROLE } from '../../../applications/users/constants/user'import type { CreateUserDto, UpdateUserDto } from '../../../applications/users/dto/create-or-update-user.dto'@@ -14,38 +14,20 @@ import { AdminUsersManager } from '../../../applications/users/services/admin-usimport { UsersManager } from '../../../applications/users/services/users-manager.service'import { comparePassword, splitFullName } from '../../../common/functions'import { configuration } from '../../../configuration/config.environment'+import { ALL_LDAP_ATTRIBUTES, LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from '../../constants/auth-ldap'import type { AUTH_SCOPE } from '../../constants/scope'import { AuthMethod } from '../../models/auth-method'-const LDAP_ATTRIBUTES = {- AD: {- SAM_ACCOUNT: 'sAMAccountName',- USER_NAME: 'userPrincipalName'- },- LDAP: {- UID: 'uid'- },- COMMON: {- MAIL: 'mail',- GIVEN_NAME: 'givenName',- SN: 'sn',- CN: 'cn',- DISPLAY_NAME: 'displayName'- }-} as const--const ALL_ATTRIBUTES = [...Object.values(LDAP_ATTRIBUTES.COMMON), ...Object.values(LDAP_ATTRIBUTES.LDAP), ...Object.values(LDAP_ATTRIBUTES.AD)]--type KnownAttr =- | (typeof LDAP_ATTRIBUTES.AD)[keyof typeof LDAP_ATTRIBUTES.AD]- | (typeof LDAP_ATTRIBUTES.LDAP)[keyof typeof LDAP_ATTRIBUTES.LDAP]- | (typeof LDAP_ATTRIBUTES.COMMON)[keyof typeof LDAP_ATTRIBUTES.COMMON]--type LdapUserEntry = Entry & Record<KnownAttr | string, string>+type LdapUserEntry = Entry & Record<LDAP_LOGIN_ATTR | (typeof LDAP_COMMON_ATTR)[keyof typeof LDAP_COMMON_ATTR], string>@Injectable()export class AuthMethodLdapService implements AuthMethod {private readonly logger = new Logger(AuthMethodLdapService.name)+ private readonly loginAttribute: LDAP_LOGIN_ATTR = configuration.auth.ldap.attributes.login+ private readonly emailAttribute: string = configuration.auth.ldap.attributes.email+ private readonly servers: string[] = configuration.auth.ldap.servers+ private readonly baseDN: string = configuration.auth.ldap.baseDN+ private readonly filter: string = configuration.auth.ldap.filterprivate clientOptions: ClientOptions = { timeout: 6000, connectTimeout: 6000, url: '' }constructor(@@ -54,8 +36,7 @@ export class AuthMethodLdapService implements AuthMethod {) {}async validateUser(login: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {- login = this.getUserLogin(login)- let user: UserModel = await this.usersManager.findUser(login, false)+ let user: UserModel = await this.usersManager.findUser(this.normalizeLogin(login), false)if (user) {if (user.isGuest) {// allow guests to be authenticated from db and check if the current user is defined as active@@ -82,9 +63,9 @@ export class AuthMethodLdapService implements AuthMethod {}}return null- } else if (!entry[configuration.auth.ldap.attributes.login] || !entry[configuration.auth.ldap.attributes.email]) {+ } else if (!entry[this.loginAttribute] || !entry[this.emailAttribute]) {this.logger.error(`${this.validateUser.name} - required ldap fields are missing :- [${configuration.auth.ldap.attributes.login}, ${configuration.auth.ldap.attributes.email}] =>+ [${this.loginAttribute}, ${this.emailAttribute}] =>(${JSON.stringify(entry)})`)return null}@@ -94,27 +75,28 @@ export class AuthMethodLdapService implements AuthMethod {return user}- private async checkAuth(uid: string, password: string): Promise<LdapUserEntry | false> {- const servers = configuration.auth.ldap.servers- const loginAttr = configuration.auth.ldap.attributes.login- const baseDN = configuration.auth.ldap.baseDN- const bindUserDN = (Object.values(LDAP_ATTRIBUTES.AD) as string[]).indexOf(loginAttr) > -1 ? loginAttr : `${loginAttr}=${uid},${baseDN}`+ private async checkAuth(login: string, password: string): Promise<LdapUserEntry | false> {+ const loginAttr = this.loginAttribute+ const isAD = loginAttr === LDAP_LOGIN_ATTR.SAM || loginAttr === LDAP_LOGIN_ATTR.UPN+ // AD: bind directly with the user input (UPN or DOMAIN\user)+ // Generic LDAP: build DN from login attribute + baseDN+ const bindUserDN = isAD ? login : `${loginAttr}=${login},${this.baseDN}`let client: Clientlet error: any- for (const s of servers) {+ for (const s of this.servers) {client = new Client({ ...this.clientOptions, url: s })try {await client.bind(bindUserDN, password)- return await this.checkAccess(client, uid)+ return await this.checkAccess(client, login)} catch (e) {if (e.errors?.length) {for (const err of e.errors) {- this.logger.warn(`${this.checkAuth.name} - ${uid} : ${err}`)+ this.logger.warn(`${this.checkAuth.name} - ${login} : ${err}`)error = err}} else {error = e- this.logger.warn(`${this.checkAuth.name} - ${uid} : ${e}`)+ this.logger.warn(`${this.checkAuth.name} - ${login} : ${e}`)}if (error instanceof InvalidCredentialsError) {return false@@ -129,71 +111,82 @@ export class AuthMethodLdapService implements AuthMethod {return false}- private async checkAccess(client: Client, uid: string): Promise<LdapUserEntry | false> {- const searchFilter = `(&(${configuration.auth.ldap.attributes.login}=${uid})${configuration.auth.ldap.filter || ''})`+ private async checkAccess(client: Client, login: string): Promise<LdapUserEntry | false> {+ const searchFilter = this.buildUserFilter(login, this.filter)try {- const { searchEntries } = await client.search(configuration.auth.ldap.baseDN, {+ const { searchEntries } = await client.search(this.baseDN, {scope: 'sub',filter: searchFilter,- attributes: ALL_ATTRIBUTES+ attributes: ALL_LDAP_ATTRIBUTES})- for (const entry of searchEntries) {- if (entry[configuration.auth.ldap.attributes.login] === uid) {- return this.convertToLdapUserEntry(entry)- }++ if (searchEntries.length === 0) {+ this.logger.debug(`${this.checkAccess.name} - search filter : ${searchFilter}`)+ this.logger.warn(`${this.checkAccess.name} - no LDAP entry found for : ${login}`)+ return false}- this.logger.warn(`${this.checkAuth.name} - unable to find user id : ${uid}`)- return false++ if (searchEntries.length > 1) {+ this.logger.warn(`${this.checkAccess.name} - multiple LDAP entries found for : ${login}, using first one`)+ }++ // Always return the first valid entry+ return this.convertToLdapUserEntry(searchEntries[0])} catch (e) {- this.logger.error(`${this.checkAccess.name} - ${uid} : ${e}`)+ this.logger.debug(`${this.checkAccess.name} - search filter : ${searchFilter}`)+ this.logger.error(`${this.checkAccess.name} - ${login} : ${e}`)return false}}private async updateOrCreateUser(identity: CreateUserDto, user: UserModel): Promise<UserModel> {if (user === null) {- return this.adminUsersManager.createUserOrGuest(identity, USER_ROLE.USER)- } else {- if (identity.login !== user.login) {- this.logger.error(`${this.updateOrCreateUser.name} - user id mismatch : ${identity.login} !== ${user.login}`)- throw new HttpException('Account matching error', HttpStatus.FORBIDDEN)+ const createdUser = await this.adminUsersManager.createUserOrGuest(identity, USER_ROLE.USER)+ const freshUser = await this.usersManager.fromUserId(createdUser.id)+ if (!freshUser) {+ this.logger.error(`${this.updateOrCreateUser.name} - user was not found : ${createdUser.login} (${createdUser.id})`)+ throw new HttpException('User not found', HttpStatus.NOT_FOUND)}- // check if user information has changed- const identityHasChanged: UpdateUserDto = Object.fromEntries(- (- await Promise.all(- Object.keys(identity).map(async (key: string) => {- if (key === 'password') {- const isSame = await comparePassword(identity[key], user.password)- return isSame ? null : [key, identity[key]]- }- return identity[key] !== user[key] ? [key, identity[key]] : null- })- )- ).filter(Boolean)- )- if (Object.keys(identityHasChanged).length > 0) {- try {- await this.adminUsersManager.updateUserOrGuest(user.id, identityHasChanged)- if (identityHasChanged?.password) {- delete identityHasChanged.password- }- Object.assign(user, identityHasChanged)- if ('lastName' in identityHasChanged || 'firstName' in identityHasChanged) {- // force fullName update- user.setFullName(true)- }- } catch (e) {- this.logger.warn(`${this.updateOrCreateUser.name} - unable to update user *${user.login}* : ${e}`)+ return freshUser+ }+ if (identity.login !== user.login) {+ this.logger.error(`${this.updateOrCreateUser.name} - user login mismatch : ${identity.login} !== ${user.login}`)+ throw new HttpException('Account matching error', HttpStatus.FORBIDDEN)+ }+ // check if user information has changed+ const identityHasChanged: UpdateUserDto = Object.fromEntries(+ (+ await Promise.all(+ Object.keys(identity).map(async (key: string) => {+ if (key === 'password') {+ const isSame = await comparePassword(identity[key], user.password)+ return isSame ? null : [key, identity[key]]+ }+ return identity[key] !== user[key] ? [key, identity[key]] : null+ })+ )+ ).filter(Boolean)+ )+ if (Object.keys(identityHasChanged).length > 0) {+ try {+ await this.adminUsersManager.updateUserOrGuest(user.id, identityHasChanged)+ if (identityHasChanged?.password) {+ delete identityHasChanged.password}+ Object.assign(user, identityHasChanged)+ if ('lastName' in identityHasChanged || 'firstName' in identityHasChanged) {+ // force fullName update in current user model+ user.setFullName(true)+ }+ } catch (e) {+ this.logger.warn(`${this.updateOrCreateUser.name} - unable to update user *${user.login}* : ${e}`)}- await user.makePaths()- return user}+ return user}private convertToLdapUserEntry(entry: Entry): LdapUserEntry {- for (const attr of ALL_ATTRIBUTES) {+ for (const attr of ALL_LDAP_ATTRIBUTES) {if (Array.isArray(entry[attr])) {entry[attr] = entry[attr].length > 0 ? entry[attr][0] : null}@@ -203,8 +196,8 @@ export class AuthMethodLdapService implements AuthMethod {private createIdentity(entry: LdapUserEntry, password: string): CreateUserDto {return {- login: this.getUserLogin(entry[configuration.auth.ldap.attributes.login]),- email: entry[configuration.auth.ldap.attributes.email],+ login: this.normalizeLogin(entry[this.loginAttribute]),+ email: entry[this.emailAttribute] as string,password: password,...this.getFirstNameAndLastName(entry)} satisfies CreateUserDto@@ -227,12 +220,28 @@ export class AuthMethodLdapService implements AuthMethod {return { firstName: '', lastName: '' }}- private getUserLogin(login: string): string {- if (configuration.auth.ldap.attributes.login === LDAP_ATTRIBUTES.AD.USER_NAME) {- return login.split('@')[0]- } else if (configuration.auth.ldap.attributes.login === LDAP_ATTRIBUTES.AD.SAM_ACCOUNT) {- return login.split('\\')[0]+ private normalizeLogin(login: string, toLowerCase = true): string {+ const normalized = (login.includes('\\') ? login.split('\\').slice(-1)[0] : login).trim()+ return toLowerCase ? normalized.toLowerCase() : normalized+ }++ private buildUserFilter(login: string, extraFilter?: string): string {+ // Build a safe LDAP filter to search for a user.+ // Important: - Values passed to EqualityFilter are auto-escaped by ldapts+ // - extraFilter is appended as-is (assumed trusted configuration)+ // Output: (&(|(userPrincipalName=john.doe)(sAMAccountName=john.doe)(uid=john.doe))(*extraFilter*))++ // OR clause: accept UPN, sAMAccountName, or uid+ const normalizedLogin = this.normalizeLogin(login, false)++ const eq = new EqualityFilter({ attribute: this.loginAttribute, value: normalizedLogin })+ // Convert to LDAP filter string+ let filterString = new AndFilter({ filters: [eq] }).toString()++ // Optionally append an extra filter from config (trusted source)+ if (extraFilter && extraFilter.trim()) {+ filterString = `(&${filterString}${extraFilter})`}- return login+ return filterString}}diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yamlindex 4af46df1..a96aa4d8 100755--- a/environment/environment.dist.yaml+++ b/environment/environment.dist.yaml@@ -120,7 +120,7 @@ auth:# filter, e.g: (acl=admin)filter:attributes:- # login attribute (e.g. `uid` | `sAMAccountName` | `userPrincipalName`)+ # login attribute: `uid` | `sAMAccountName` | `userPrincipalName`# default: `uid`login: uid# email attribute: `mail` or `email`