Skip to content

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

fix(backend:ldap): harden direct-bind identity resolution

johaven710129641a95
diff --git a/backend/src/authentication/providers/ldap/auth-ldap.interface.ts b/backend/src/authentication/providers/ldap/auth-ldap.interface.ts
index a7cb7597..f9e277ea 100644
--- a/backend/src/authentication/providers/ldap/auth-ldap.interface.ts
+++ b/backend/src/authentication/providers/ldap/auth-ldap.interface.ts
@@ -6,4 +6,10 @@ export type LdapUserEntry = Entry &
Record<LDAP_LOGIN_ATTR | Exclude<(typeof LDAP_COMMON_ATTR)[keyof typeof LDAP_COMMON_ATTR], typeof LDAP_COMMON_ATTR.MEMBER_OF>, string> & {
[LDAP_COMMON_ATTR.MEMBER_OF]?: string[]
}
+
+export interface LdapUserCandidate {
+ rawEntry: Entry
+ userDn: string
+}
+
export type LdapCa = ConnectionOptions['ca']
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 a0da22b7..1edb4c4c 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,6 +1,6 @@
import { HttpStatus } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
-import { Client, InvalidCredentialsError } from 'ldapts'
+import { Client, InsufficientAccessError, InvalidCredentialsError, SizeLimitExceededError } from 'ldapts'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
@@ -107,6 +107,20 @@ describe(AuthProviderLDAP.name, () => {
ldapClient.search.mockResolvedValue({ searchEntries: entries })
}
+ const expectRejectedLdapAuthentication = async (expectedSearches: number, expectedBinds: number) => {
+ usersManager.findUser.mockResolvedValue(null)
+ usersManager.validateLocalPasswordForUser.mockResolvedValue(null)
+
+ const result = await authProviderLDAP.validateUser('john', 'pwd')
+
+ expect(result).toBeNull()
+ expect(ldapClient.search).toHaveBeenCalledTimes(expectedSearches)
+ expect(ldapClient.bind).toHaveBeenCalledTimes(expectedBinds)
+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()
+ expect(adminUsersManager.createUserOrGuest).not.toHaveBeenCalled()
+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
+ }
+
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
@@ -148,13 +162,6 @@ describe(AuthProviderLDAP.name, () => {
vi.restoreAllMocks()
})
- it('should be defined', () => {
- expect(authProviderLDAP).toBeDefined()
- expect(usersManager).toBeDefined()
- expect(adminUsersManager).toBeDefined()
- expect(ldapClient).toBeDefined()
- })
-
it('should authenticate a guest user via database and bypass LDAP', async () => {
const guestUser: any = { id: 1, login: 'guest1', isGuest: true, isActive: true }
usersManager.findUser.mockResolvedValue(guestUser)
@@ -239,23 +246,6 @@ describe(AuthProviderLDAP.name, () => {
expect(usersManager.updateAccesses).not.toHaveBeenCalled()
})
- it('should return null when LDAP search yields no entries or throws', async () => {
- const existingUser: any = buildUser({ id: 10 })
- usersManager.findUser.mockResolvedValue(existingUser)
- mockBindResolve()
- mockSearchEntries([])
-
- const resA = await authProviderLDAP.validateUser('john', 'pwd')
-
- expect(resA).toBeNull()
-
- ldapClient.search.mockRejectedValue(new Error('search failed'))
- const resB = await authProviderLDAP.validateUser('john', 'pwd')
-
- expect(resB).toBeNull()
- expect(usersManager.updateAccesses).not.toHaveBeenCalled()
- })
-
it('should fallback to local auth when LDAP is unavailable and fallback is enabled', async () => {
setLdapConfig({ options: { enablePasswordAuthFallback: true } })
const existingUser: any = buildUser({ id: 2 })
@@ -508,6 +498,112 @@ describe(AuthProviderLDAP.name, () => {
expect(res).toBe(createdUser)
})
+ it('should bind and read the exact DN for generic LDAP direct bind', async () => {
+ setLdapConfig({ filter: '(department=IT)' })
+ usersManager.findUser.mockResolvedValue(null)
+ mockBindResolve()
+ ldapClient.search.mockResolvedValueOnce({
+ searchEntries: [{ uid: 'john', cn: 'John Doe', mail: '[email protected]', dn: 'uid=john,ou=people,dc=example,dc=org' }]
+ })
+ const createdUser: any = { id: 4, login: 'john', isGuest: false, isActive: true, makePaths: vi.fn() }
+ adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
+ usersManager.fromUserId.mockResolvedValue(createdUser)
+
+ await authProviderLDAP.validateUser('DOMAIN\\john', 'pwd')
+
+ const bindUserDN = 'uid=john,ou=people,dc=example,dc=org'
+ expect(ldapClient.bind).toHaveBeenCalledWith(bindUserDN, 'pwd')
+ expect(ldapClient.search).toHaveBeenCalledWith(bindUserDN, {
+ scope: 'base',
+ filter: '(&(objectClass=*)(department=IT))',
+ attributes: (authProviderLDAP as any).requestedAttributes,
+ sizeLimit: 1
+ })
+ })
+
+ it('should use a verified subtree fallback when the exact LDAP entry cannot be read', async () => {
+ setLdapConfig({ filter: '(department=IT)' })
+ usersManager.findUser.mockResolvedValue(null)
+ mockBindResolve()
+ const fallbackUserDN = 'UID=john,OU=people,DC=example,DC=org'
+ ldapClient.search.mockRejectedValueOnce(new InsufficientAccessError('base read denied')).mockResolvedValueOnce({
+ searchEntries: [{ uid: 'john', cn: 'John Doe', mail: '[email protected]', dn: fallbackUserDN }]
+ })
+ const createdUser: any = { id: 4, login: 'john', isGuest: false, isActive: true, makePaths: vi.fn() }
+ adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
+ usersManager.fromUserId.mockResolvedValue(createdUser)
+
+ const res = await authProviderLDAP.validateUser('DOMAIN\\john', 'pwd')
+
+ const bindUserDN = 'uid=john,ou=people,dc=example,dc=org'
+ expect(ldapClient.search).toHaveBeenNthCalledWith(1, bindUserDN, {
+ scope: 'base',
+ filter: '(&(objectClass=*)(department=IT))',
+ attributes: (authProviderLDAP as any).requestedAttributes,
+ sizeLimit: 1
+ })
+ expect(ldapClient.search).toHaveBeenNthCalledWith(2, 'ou=people,dc=example,dc=org', {
+ scope: 'sub',
+ filter: '(&(uid=john)(department=IT))',
+ attributes: (authProviderLDAP as any).requestedAttributes
+ })
+ expect(ldapClient.bind).toHaveBeenNthCalledWith(1, bindUserDN, 'pwd')
+ expect(ldapClient.bind).toHaveBeenNthCalledWith(2, fallbackUserDN, 'pwd')
+ expect(res).toBe(createdUser)
+ })
+
+ it('should not use the subtree fallback when the exact entry does not match the configured filter', async () => {
+ setLdapConfig({ filter: '(department=IT)' })
+ mockBindResolve()
+ ldapClient.search.mockResolvedValueOnce({ searchEntries: [] })
+
+ await expectRejectedLdapAuthentication(1, 1)
+ })
+
+ it('should reject an ambiguous direct-bind fallback', async () => {
+ mockBindResolve()
+ ldapClient.search.mockRejectedValueOnce(new InsufficientAccessError('base read denied')).mockResolvedValueOnce({
+ searchEntries: [
+ { uid: 'john', mail: '[email protected]', dn: 'uid=john,ou=people,dc=example,dc=org' },
+ { uid: 'john', mail: '[email protected]', dn: 'uid=john,ou=other,dc=example,dc=org' }
+ ]
+ })
+
+ await expectRejectedLdapAuthentication(2, 1)
+ })
+
+ it('should reject a truncated direct-bind fallback before binding a candidate', async () => {
+ mockBindResolve()
+ ldapClient.search
+ .mockRejectedValueOnce(new InsufficientAccessError('base read denied'))
+ .mockRejectedValueOnce(new SizeLimitExceededError('server search limit reached'))
+
+ await expectRejectedLdapAuthentication(2, 1)
+ })
+
+ it('should not use the subtree fallback for an unexpected exact-entry error', async () => {
+ mockBindResolve()
+ ldapClient.search.mockRejectedValueOnce(new Error('unexpected search failure'))
+
+ await expectRejectedLdapAuthentication(1, 1)
+ })
+
+ it('should reject a fallback entry that does not accept the submitted password', async () => {
+ ldapClient.unbind.mockResolvedValue(undefined)
+ ldapClient.bind.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new InvalidCredentialsError('invalid credentials'))
+ ldapClient.search.mockRejectedValueOnce(new InsufficientAccessError('base read denied')).mockResolvedValueOnce({
+ searchEntries: [{ uid: 'john', mail: '[email protected]', dn: 'uid=john,ou=people,dc=example,dc=org' }]
+ })
+
+ await expectRejectedLdapAuthentication(2, 2)
+ })
+
+ it('should escape the generic LDAP login when building the bind DN', () => {
+ const bindUserDN = (authProviderLDAP as any).buildBindUserDN('john,ops\\team')
+
+ expect(bindUserDN).toBe('uid=john\\,ops\\\\team,ou=people,dc=example,dc=org')
+ })
+
it('should use service bind for LDAP searches when configured', async () => {
setLdapConfig({
serviceBindDN: 'cn=svc,dc=example,dc=org',
@@ -526,6 +622,7 @@ describe(AuthProviderLDAP.name, () => {
expect(ldapClient.bind).toHaveBeenCalledWith('cn=svc,dc=example,dc=org', 'secret')
expect(ldapClient.bind).toHaveBeenCalledWith('uid=john,ou=people,dc=example,dc=org', 'pwd')
+ expect(ldapClient.search).toHaveBeenCalledWith('ou=people,dc=example,dc=org', expect.objectContaining({ scope: 'sub' }))
})
it('should return null when service bind is set but user DN is not found', async () => {
@@ -536,10 +633,13 @@ describe(AuthProviderLDAP.name, () => {
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
ldapClient.search.mockResolvedValueOnce({ searchEntries: [] })
+ const warnSpy = vi.spyOn(authProviderLDAP['logger'], 'warn').mockImplementation(() => undefined)
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(res).toBeNull()
+ expect(warnSpy).toHaveBeenCalledOnce()
+ expect(warnSpy).toHaveBeenCalledWith(expect.objectContaining({ tag: 'findUserEntry' }))
expect(ldapClient.bind).toHaveBeenCalledWith('cn=svc,dc=example,dc=org', 'secret')
expect(ldapClient.bind).not.toHaveBeenCalledWith('uid=john,ou=people,dc=example,dc=org', 'pwd')
})
@@ -632,6 +732,10 @@ describe(AuthProviderLDAP.name, () => {
expect(ldapFilter).toContain('(cn=john)')
expect(ldapFilter).toContain('(mail=john)')
expect(ldapFilter).toContain('(department=IT)')
+
+ setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.SAM }, netbiosName: 'SYNC' })
+ const samLogin = (authProviderLDAP as any).buildLdapLogin('john')
+ expect(samLogin).toBe('SYNC\\john')
})
it('should normalize LDAP entries for memberOf and array attributes', () => {
@@ -648,12 +752,6 @@ describe(AuthProviderLDAP.name, () => {
expect(normalized.memberOf).toEqual(['CN=Admins,OU=Groups,DC=example,DC=org', 'Admins', 'CN=Staff,OU=Groups,DC=example,DC=org', 'Staff'])
})
- it('should build LDAP logins for SAM account name when netbiosName is set', () => {
- setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.SAM }, netbiosName: 'SYNC' })
- const samLogin = (authProviderLDAP as any).buildLdapLogin('john')
- expect(samLogin).toBe('SYNC\\john')
- })
-
it('should load CA from file and keep inline CA values', async () => {
const tmpPath = await mkdtemp(path.join(tmpdir(), 'ldap-tls-'))
const caPath = path.join(tmpPath, 'ca.pem')
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 7918bdc1..ec2715c0 100644
--- a/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
+++ b/backend/src/authentication/providers/ldap/auth-provider-ldap.service.ts
@@ -1,5 +1,17 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
-import { AndFilter, Client, ClientOptions, Entry, EqualityFilter, InvalidCredentialsError, OrFilter } from 'ldapts'
+import type { ClientOptions, Entry } from 'ldapts'
+import {
+ AndFilter,
+ Client,
+ DN,
+ EqualityFilter,
+ InsufficientAccessError,
+ InvalidCredentialsError,
+ NoSuchObjectError,
+ OrFilter,
+ PresenceFilter,
+ UnwillingToPerformError
+} from 'ldapts'
import { readFile } from 'node:fs/promises'
import { CONNECT_ERROR_CODE } from '../../../app.constants.js'
import { isPathIsReadable } from '../../../applications/files/utils/files.js'
@@ -15,7 +27,7 @@ import { AuthProvider } from '../auth-providers.models.js'
import { applyStorageQuotaToIdentity } from '../auth-providers.utils.js'
import type { AuthProviderLDAPConfig } from './auth-ldap.config.js'
import { ALL_LDAP_ATTRIBUTES, LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR, LDAP_SEARCH_ATTR } from './auth-ldap.constants.js'
-import type { LdapCa, LdapUserEntry } from './auth-ldap.interface.js'
+import type { LdapCa, LdapUserCandidate, LdapUserEntry } from './auth-ldap.interface.js'
@Injectable()
export class AuthProviderLDAP implements AuthProvider {
@@ -105,7 +117,9 @@ export class AuthProviderLDAP implements AuthProvider {
private async checkAuth(login: string, password: string): Promise<LdapUserEntry | false> {
// Bind and fetch LDAP entry, optionally via service account.
- const ldapLogin = this.buildLdapLogin(login)
+ // Generic LDAP uses the same canonical login for both the bind DN and the
+ // local account mapping. AD keeps the submitted UPN or DOMAIN\user form.
+ const ldapLogin = this.buildLdapLogin(this.isAD ? login : this.dbLogin(login))
// AD: bind directly with the user input (UPN or DOMAIN\user)
// Generic LDAP: build DN from login attribute + baseDN
const bindUserDN = this.buildBindUserDN(ldapLogin)
@@ -119,8 +133,11 @@ export class AuthProviderLDAP implements AuthProvider {
attemptedBindDN = this.ldapConfig.serviceBindDN
await client.bind(this.ldapConfig.serviceBindDN, this.ldapConfig.serviceBindPassword)
const result = await this.findUserEntry(ldapLogin, client)
- if (!result || !result.userDn) {
- this.logger.warn({ tag: this.checkAuth.name, msg: `no LDAP entry found for : ${login}` })
+ if (!result) {
+ return false
+ }
+ if (!result.userDn) {
+ this.logger.warn({ tag: this.checkAuth.name, msg: `LDAP entry has no DN for : ${login}` })
return false
}
const { entry, userDn } = result
@@ -130,7 +147,7 @@ export class AuthProviderLDAP implements AuthProvider {
}
attemptedBindDN = bindUserDN
await client.bind(bindUserDN, password)
- return await this.checkAccess(ldapLogin, client, bindUserDN)
+ return this.isAD ? await this.checkAccess(ldapLogin, client, bindUserDN) : await this.checkAccessByDN(bindUserDN, ldapLogin, password, client)
} catch (e) {
error = this.handleBindError(e, attemptedBindDN)
if (error instanceof InvalidCredentialsError) {
@@ -197,6 +214,99 @@ export class AuthProviderLDAP implements AuthProvider {
return result ? result.entry : false
}
+ private async checkAccessByDN(bindUserDN: string, ldapLogin: string, password: string, client: Client): Promise<LdapUserEntry | false> {
+ // A generic direct bind must read back the exact entry that was authenticated.
+ try {
+ const result = await this.findUserEntryByDN(bindUserDN, client)
+ return result ? result.entry : false
+ } catch (e) {
+ if (!this.canFallbackFromExactEntryRead(e)) {
+ throw e
+ }
+
+ this.logger.warn({
+ tag: this.checkAccessByDN.name,
+ msg: `exact LDAP entry read unavailable for bind DN, using verified subtree fallback : ${bindUserDN} : ${e}`
+ })
+ const candidate = await this.findDirectBindFallbackCandidate(ldapLogin, client)
+ if (!candidate) {
+ return false
+ }
+
+ try {
+ // Prove that the fallback entry accepts the same credentials before
+ // using any of its attributes for the local identity.
+ await client.bind(candidate.userDn, password)
+ } catch (bindError) {
+ const error = this.handleBindError(bindError, candidate.userDn)
+ if (error instanceof InvalidCredentialsError) {
+ return false
+ }
+ throw error
+ }
+
+ const result = await this.buildUserEntryResult(candidate.rawEntry, client, candidate.userDn)
+ return result.entry
+ }
+ }
+
+ private async findUserEntryByDN(bindUserDN: string, client: Client): Promise<{ entry: LdapUserEntry; userDn?: string } | false> {
+ const searchFilter = this.buildBaseUserFilter(this.ldapConfig.filter)
+ try {
+ const { searchEntries } = await client.search(bindUserDN, {
+ scope: LDAP_SEARCH_ATTR.BASE,
+ filter: searchFilter,
+ attributes: this.requestedAttributes,
+ sizeLimit: 1
+ })
+
+ if (searchEntries.length !== 1) {
+ this.logger.debug({ tag: this.findUserEntryByDN.name, msg: `search filter : ${searchFilter}` })
+ this.logger.warn({ tag: this.findUserEntryByDN.name, msg: `LDAP entry not found for bind DN : ${bindUserDN}` })
+ return false
+ }
+
+ return await this.buildUserEntryResult(searchEntries[0], client, bindUserDN)
+ } catch (e) {
+ this.logger.debug({ tag: this.findUserEntryByDN.name, msg: `search filter : ${searchFilter}` })
+ this.logger.error({ tag: this.findUserEntryByDN.name, msg: `${bindUserDN} : ${e}` })
+ throw e
+ }
+ }
+
+ private async findDirectBindFallbackCandidate(ldapLogin: string, client: Client): Promise<LdapUserCandidate | false> {
+ const searchFilter = this.buildConfiguredLoginFilter(ldapLogin, this.ldapConfig.filter)
+ try {
+ const { searchEntries } = await client.search(this.ldapConfig.baseDN, {
+ scope: LDAP_SEARCH_ATTR.SUB,
+ filter: searchFilter,
+ attributes: this.requestedAttributes
+ })
+
+ if (searchEntries.length !== 1) {
+ this.logger.debug({ tag: this.findDirectBindFallbackCandidate.name, msg: `search filter : ${searchFilter}` })
+ this.logger.warn({
+ tag: this.findDirectBindFallbackCandidate.name,
+ msg: `expected one LDAP fallback entry for : ${ldapLogin}, found : ${searchEntries.length}`
+ })
+ return false
+ }
+
+ const rawEntry = searchEntries[0]
+ const userDn = rawEntry.dn
+ if (!userDn) {
+ this.logger.warn({ tag: this.findDirectBindFallbackCandidate.name, msg: `LDAP fallback entry has no DN for : ${ldapLogin}` })
+ return false
+ }
+
+ return { rawEntry, userDn }
+ } catch (e) {
+ this.logger.debug({ tag: this.findDirectBindFallbackCandidate.name, msg: `search filter : ${searchFilter}` })
+ this.logger.error({ tag: this.findDirectBindFallbackCandidate.name, msg: `${ldapLogin} : ${e}` })
+ throw e
+ }
+ }
+
private async findUserEntry(login: string, client: Client, bindUserDN?: string): Promise<{ entry: LdapUserEntry; userDn?: string } | false> {
const searchFilter = this.buildUserFilter(login, this.ldapConfig.filter)
try {
@@ -216,19 +326,8 @@ export class AuthProviderLDAP implements AuthProvider {
this.logger.warn({ tag: this.findUserEntry.name, msg: `multiple LDAP entries found for : ${login}, using first one` })
}
- const rawEntry = searchEntries[0]
- const entry: LdapUserEntry = this.convertToLdapUserEntry(rawEntry)
- const userDn = (rawEntry as { dn?: string }).dn || bindUserDN
-
- if (this.ldapConfig.options.adminGroup && !this.hasAdminGroup(entry, this.ldapConfig.options.adminGroup)) {
- if (userDn && (await this.isMemberOfGroupOfNames(this.ldapConfig.options.adminGroup, userDn, client))) {
- const existing = Array.isArray(entry[LDAP_COMMON_ATTR.MEMBER_OF]) ? entry[LDAP_COMMON_ATTR.MEMBER_OF] : []
- entry[LDAP_COMMON_ATTR.MEMBER_OF] = [...new Set([...existing, this.ldapConfig.options.adminGroup])]
- }
- }
-
// Return the first matching entry.
- return { entry, userDn }
+ return await this.buildUserEntryResult(searchEntries[0], client, bindUserDN)
} catch (e) {
this.logger.debug({ tag: this.findUserEntry.name, msg: `search filter : ${searchFilter}` })
this.logger.error({ tag: this.findUserEntry.name, msg: `${login} : ${e}` })
@@ -236,6 +335,20 @@ export class AuthProviderLDAP implements AuthProvider {
}
}
+ private async buildUserEntryResult(rawEntry: Entry, client: Client, fallbackUserDn?: string): Promise<{ entry: LdapUserEntry; userDn?: string }> {
+ const entry: LdapUserEntry = this.convertToLdapUserEntry(rawEntry)
+ const userDn = (rawEntry as { dn?: string }).dn || fallbackUserDn
+
+ if (this.ldapConfig.options.adminGroup && !this.hasAdminGroup(entry, this.ldapConfig.options.adminGroup)) {
+ if (userDn && (await this.isMemberOfGroupOfNames(this.ldapConfig.options.adminGroup, userDn, client))) {
+ const existing = Array.isArray(entry[LDAP_COMMON_ATTR.MEMBER_OF]) ? entry[LDAP_COMMON_ATTR.MEMBER_OF] : []
+ entry[LDAP_COMMON_ATTR.MEMBER_OF] = [...new Set([...existing, this.ldapConfig.options.adminGroup])]
+ }
+ }
+
+ return { entry, userDn }
+ }
+
private async updateOrCreateUser(identity: CreateUserDto, user: UserModel): Promise<UserModel> {
// Create or update the local user record from LDAP identity.
if (user === null) {
@@ -384,7 +497,21 @@ export class AuthProviderLDAP implements AuthProvider {
}
private buildBindUserDN(ldapLogin: string): string {
- return this.isAD ? ldapLogin : `${this.ldapConfig.attributes.login}=${ldapLogin},${this.ldapConfig.baseDN}`
+ if (this.isAD) {
+ return ldapLogin
+ }
+ const userRdn = new DN().addPairRDN(this.ldapConfig.attributes.login, ldapLogin).toString()
+ return `${userRdn},${this.ldapConfig.baseDN}`
+ }
+
+ private buildBaseUserFilter(extraFilter?: string): string {
+ const presenceFilter = new PresenceFilter({ attribute: LDAP_SEARCH_ATTR.OBJECT_CLASS }).toString()
+ return extraFilter?.trim() ? `(&${presenceFilter}${extraFilter})` : presenceFilter
+ }
+
+ private buildConfiguredLoginFilter(login: string, extraFilter?: string): string {
+ const loginFilter = new EqualityFilter({ attribute: this.ldapConfig.attributes.login, value: login }).toString()
+ return extraFilter?.trim() ? `(&${loginFilter}${extraFilter})` : loginFilter
}
private buildUserFilter(login: string, extraFilter?: string): string {
@@ -466,6 +593,10 @@ export class AuthProviderLDAP implements AuthProvider {
return { dn: adminGroup, cn }
}
+ private canFallbackFromExactEntryRead(error: unknown): boolean {
+ return error instanceof InsufficientAccessError || error instanceof NoSuchObjectError || error instanceof UnwillingToPerformError
+ }
+
private handleBindError(error: any, attemptedBindDN: string): InvalidCredentialsError | any {
// Prefer the most specific LDAP error when multiple errors are returned.
if (error?.errors?.length) {
diff --git a/backend/src/authentication/providers/ldap/ldap.md b/backend/src/authentication/providers/ldap/ldap.md
index 0b3b9c90..10283794 100644
--- a/backend/src/authentication/providers/ldap/ldap.md
+++ b/backend/src/authentication/providers/ldap/ldap.md
@@ -44,6 +44,14 @@ For generic LDAP, the bind DN is constructed as:
<attributes.login>=<login>,<baseDN>
```
+The login value is escaped as an LDAP RDN. After a successful direct bind, Sync-in reads the bound entry itself with a base-scope search at that exact
+DN. This keeps the authenticated LDAP principal and the local identity mapped from LDAP attributes tied to the same directory entry.
+
+A successful exact-entry search that returns no entry, including because the optional configured `filter` rejects it, ends authentication. If the
+directory rejects the exact read with a known access or compatibility error, Sync-in uses a guarded compatibility path: it searches under `baseDN`
+for the configured `attributes.login`, requires exactly one complete, non-truncated result with a DN, then binds that exact DN with the same password
+before using any of its attributes. Other read errors do not enable this compatibility search.
+
For Active Directory login attributes, Sync-in binds with the login string directly instead of constructing a DN:
- `userPrincipalName` can append `upnSuffix` when the user enters `john` instead of `[email protected]`;
@@ -75,8 +83,11 @@ limit complements both the directory policy and Sync-in's per-IP limits. Account
## User search
-User searches run under `baseDN` with subtree scope. Sync-in asks LDAP for the known login attributes, common profile attributes, the configured email
-attribute, and the configured storage quota attribute.
+Service-bind searches and Active Directory direct-bind searches run under `baseDN` with subtree scope. Generic LDAP direct bind instead reads the exact
+bound user DN with base scope. Its guarded compatibility search, when needed after a known exact-read error, uses subtree scope and matches only the
+configured `attributes.login`; it never uses the broader generic LDAP OR filter. All modes ask LDAP for the known login attributes, common profile
+attributes, the configured email attribute, and the configured storage quota attribute. The optional trusted `filter` applies to both the exact-entry
+read and its guarded compatibility search.
For Active Directory mode, the search filter matches any of:
@@ -86,7 +97,7 @@ userPrincipalName
mail
```
-For generic LDAP mode, the search filter matches any of:
+For generic LDAP service-bind mode, the search filter matches any of:
```text
uid
@@ -97,7 +108,9 @@ mail
The login value placed in these comparisons is escaped by `ldapts`. The configured `filter` is then appended as-is and is treated as trusted
administrator configuration, not user input.
-If multiple entries match, Sync-in logs a warning and uses the first entry returned by LDAP.
+If multiple entries match a normal service-bind or Active Directory subtree search, Sync-in logs a warning and uses the first entry returned by LDAP.
+A generic direct-bind base search and its guarded compatibility search must each identify exactly one entry; an ambiguous compatibility result is
+rejected, as is any result reported as truncated by the directory.
## Supported attributes