Skip to content

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

feat(backend:auth): add support for AD-specific LDAP attributes

johaven9b682999b0f3
diff --git a/backend/src/applications/users/models/user.model.ts b/backend/src/applications/users/models/user.model.ts
index a62011a3..0ad9349b 100644
--- a/backend/src/applications/users/models/user.model.ts
+++ b/backend/src/applications/users/models/user.model.ts
@@ -170,8 +170,8 @@ export class UserModel implements User {
delete this.password
}
- setFullName() {
- if (!this.fullName) {
+ setFullName(force = false) {
+ if (!this.fullName || force) {
this.fullName = `${this.firstName || ''} ${this.lastName || ''}`.trim()
}
}
diff --git a/backend/src/authentication/auth.config.ts b/backend/src/authentication/auth.config.ts
index 837544fa..f850838f 100644
--- a/backend/src/authentication/auth.config.ts
+++ b/backend/src/authentication/auth.config.ts
@@ -109,6 +109,18 @@ export class AuthTokenConfig {
ws: AuthTokenWSConfig
}
+export class AuthMethodLdapAttributesConfig {
+ @IsOptional()
+ @IsString()
+ @Transform(({ value }) => value || 'uid')
+ login? = 'uid'
+
+ @IsOptional()
+ @IsString()
+ @Transform(({ value }) => value || 'mail')
+ email? = 'mail'
+}
+
export class AuthMethodLdapConfig {
@Transform(({ value }) => (Array.isArray(value) ? value.filter((v: string) => Boolean(v)) : value))
@ArrayNotEmpty()
@@ -124,10 +136,12 @@ export class AuthMethodLdapConfig {
@IsString()
filter?: string
- @IsString()
- @IsNotEmpty()
- @IsIn(['uid', 'mail'])
- loginAttribute = 'uid'
+ @IsDefined()
+ @IsNotEmptyObject()
+ @IsObject()
+ @ValidateNested()
+ @Type(() => AuthMethodLdapAttributesConfig)
+ attributes: AuthMethodLdapAttributesConfig = new AuthMethodLdapAttributesConfig()
}
export class AuthConfig {
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 52804ed1..5540810c 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,15 +5,15 @@
*/
import { Test, TestingModule } from '@nestjs/testing'
+import { Mocked } from 'jest-mock'
+import { Client, InvalidCredentialsError } from 'ldapts'
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'
+import { configuration } from '../../../configuration/config.environment'
+import { AuthMethodLdapService } from './auth-method-ldap.service'
// Mock ldapts Client to simulate LDAP behaviors
jest.mock('ldapts', () => {
@@ -102,7 +102,12 @@ 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'], loginAttribute: 'uid', baseDN: 'ou=people,dc=example,dc=org', filter: '' }
+ configuration.auth.ldap = {
+ servers: ['ldap://localhost:389'],
+ attributes: { login: 'uid', email: 'mail' },
+ baseDN: 'ou=people,dc=example,dc=org',
+ filter: ''
+ }
})
it('should be defined', () => {
@@ -137,15 +142,10 @@ describe(AuthMethodLdapService.name, () => {
// Phase 2: mismatch between requested login and LDAP returned login
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)
-
- // restore the attribute to avoid impacting other tests
- configuration.auth.ldap.loginAttribute = originalAttr
+ await expect(authMethodLdapService.validateUser('john', 'pwd')).resolves.toEqual(null)
})
it('should handle invalid LDAP credentials for both existing and unknown users', async () => {
@@ -355,7 +355,7 @@ describe(AuthMethodLdapService.name, () => {
usersManager.findUser.mockResolvedValue(existingUser)
// Ensure LDAP loginAttribute matches uid for this test (a previous test sets it to 'cn')
- configuration.auth.ldap.loginAttribute = 'uid'
+ configuration.auth.ldap.attributes.login = 'uid'
setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
adminUsersManager.updateUserOrGuest.mockRejectedValue(new Error('db error'))
@@ -378,7 +378,7 @@ 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.loginAttribute = 'uid'
+ 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]' }] })
@@ -392,7 +392,7 @@ describe(AuthMethodLdapService.name, () => {
jest.clearAllMocks()
const userB: any = buildUser({ id: 21, email: '[email protected]' })
usersManager.findUser.mockResolvedValue(userB)
- configuration.auth.ldap.loginAttribute = 'uid'
+ configuration.auth.ldap.attributes.login = 'uid'
setupLdapSuccess([{ uid: 'john', cn: 'John Doe', mail: '[email protected]' }])
adminUsersManager.updateUserOrGuest.mockResolvedValue(undefined)
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 135ac16f..093214b8 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
@@ -17,12 +17,35 @@ import { configuration } from '../../../configuration/config.environment'
import type { AUTH_SCOPE } from '../../constants/scope'
import { AuthMethod } from '../../models/auth-method'
-type LdapUserEntry = Entry & { uid: string; mail: string; cn: string }
+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>
@Injectable()
export class AuthMethodLdapService implements AuthMethod {
private readonly logger = new Logger(AuthMethodLdapService.name)
- private readonly entryAttributes = ['uid', 'mail', 'cn']
private clientOptions: ClientOptions = { timeout: 6000, connectTimeout: 6000, url: '' }
constructor(
@@ -30,8 +53,9 @@ export class AuthMethodLdapService implements AuthMethod {
private readonly adminUsersManager: AdminUsersManager
) {}
- async validateUser(loginOrEmail: string, password: string, ip?: string, scope?: AUTH_SCOPE): Promise<UserModel> {
- let user: UserModel = await this.usersManager.findUser(loginOrEmail, false)
+ 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)
if (user) {
if (user.isGuest) {
// allow guests to be authenticated from db and check if the current user is defined as active
@@ -42,7 +66,7 @@ export class AuthMethodLdapService implements AuthMethod {
throw new HttpException('Account locked', HttpStatus.FORBIDDEN)
}
}
- const entry: false | LdapUserEntry = await this.checkAuth(loginOrEmail, password)
+ const entry: false | LdapUserEntry = await this.checkAuth(login, password)
if (entry === false) {
// LDAP auth failed
if (user) {
@@ -58,11 +82,13 @@ export class AuthMethodLdapService implements AuthMethod {
}
}
return null
- } else if (!entry.mail || !entry.uid) {
- this.logger.error(`${this.validateUser.name} - ${loginOrEmail} : some ldap fields are missing => (${JSON.stringify(entry)})`)
+ } else if (!entry[configuration.auth.ldap.attributes.login] || !entry[configuration.auth.ldap.attributes.email]) {
+ this.logger.error(`${this.validateUser.name} - required ldap fields are missing :
+ [${configuration.auth.ldap.attributes.login}, ${configuration.auth.ldap.attributes.email}] =>
+ (${JSON.stringify(entry)})`)
return null
}
- const identity = { login: entry.uid, email: entry.mail, password: password, ...splitFullName(entry.cn) } satisfies CreateUserDto
+ const identity = this.createIdentity(entry, password)
user = await this.updateOrCreateUser(identity, user)
this.usersManager.updateAccesses(user, ip, true).catch((e: Error) => this.logger.error(`${this.validateUser.name} : ${e}`))
return user
@@ -70,7 +96,9 @@ export class AuthMethodLdapService implements AuthMethod {
private async checkAuth(uid: string, password: string): Promise<LdapUserEntry | false> {
const servers = configuration.auth.ldap.servers
- const bindUserDN = `${configuration.auth.ldap.loginAttribute}=${uid},${configuration.auth.ldap.baseDN}`
+ 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}`
let client: Client
let error: any
for (const s of servers) {
@@ -102,25 +130,22 @@ export class AuthMethodLdapService implements AuthMethod {
}
private async checkAccess(client: Client, uid: string): Promise<LdapUserEntry | false> {
- const searchFilter = `(&(${configuration.auth.ldap.loginAttribute}=${uid})${configuration.auth.ldap.filter || ''})`
+ const searchFilter = `(&(${configuration.auth.ldap.attributes.login}=${uid})${configuration.auth.ldap.filter || ''})`
try {
const { searchEntries } = await client.search(configuration.auth.ldap.baseDN, {
scope: 'sub',
filter: searchFilter,
- attributes: this.entryAttributes
+ attributes: ALL_ATTRIBUTES
})
for (const entry of searchEntries) {
- if (entry[configuration.auth.ldap.loginAttribute] === uid) {
- if (Array.isArray(entry.mail)) {
- // handles the case of multiple emails, keep the first
- entry.mail = entry.mail[0]
- }
- return entry as LdapUserEntry
+ if (entry[configuration.auth.ldap.attributes.login] === uid) {
+ return this.convertToLdapUserEntry(entry)
}
}
+ this.logger.warn(`${this.checkAuth.name} - unable to find user id : ${uid}`)
return false
} catch (e) {
- this.logger.warn(`${this.checkAccess.name} - ${uid} : ${e}`)
+ this.logger.error(`${this.checkAccess.name} - ${uid} : ${e}`)
return false
}
}
@@ -154,6 +179,10 @@ export class AuthMethodLdapService implements AuthMethod {
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}`)
}
@@ -162,4 +191,48 @@ export class AuthMethodLdapService implements AuthMethod {
return user
}
}
+
+ private convertToLdapUserEntry(entry: Entry): LdapUserEntry {
+ for (const attr of ALL_ATTRIBUTES) {
+ if (Array.isArray(entry[attr])) {
+ entry[attr] = entry[attr].length > 0 ? entry[attr][0] : null
+ }
+ }
+ return entry as LdapUserEntry
+ }
+
+ private createIdentity(entry: LdapUserEntry, password: string): CreateUserDto {
+ return {
+ login: this.getUserLogin(entry[configuration.auth.ldap.attributes.login]),
+ email: entry[configuration.auth.ldap.attributes.email],
+ password: password,
+ ...this.getFirstNameAndLastName(entry)
+ } satisfies CreateUserDto
+ }
+
+ private getFirstNameAndLastName(entry: LdapUserEntry): { firstName: string; lastName: string } {
+ // 1) Prefer structured attributes
+ if (entry.sn && entry.givenName) {
+ return { firstName: entry.givenName, lastName: entry.sn }
+ }
+ // 2) Fallback to displayName if available
+ if (entry.displayName && entry.displayName.trim()) {
+ return splitFullName(entry.displayName)
+ }
+ // 3) Fallback to cn
+ if (entry.cn && entry.cn.trim()) {
+ return splitFullName(entry.cn)
+ }
+ // 4) Nothing usable
+ 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]
+ }
+ return login
+ }
}
diff --git a/backend/src/common/functions.ts b/backend/src/common/functions.ts
index fe5d814a..1b6cb385 100755
--- a/backend/src/common/functions.ts
+++ b/backend/src/common/functions.ts
@@ -82,9 +82,13 @@ export function anonymizePassword(obj: { password?: string; secrets?: string })
return { ...obj, ...(obj?.password && { password: '********' }), ...(obj?.secrets && { secrets: '********' }) }
}
-export function splitFullName(fullName: string): { firstName: string; lastName: string } {
+export function splitFullName(fullName?: string): { firstName: string; lastName: string } {
+ if (!fullName || !fullName.trim()) return { firstName: '', lastName: '' }
const parts = fullName.trim().split(/\s+/)
- const lastName = parts.pop()
+ if (parts.length === 1) {
+ return { firstName: '', lastName: parts[0] }
+ }
+ const lastName = parts.pop()!
const firstName = parts.join(' ')
return { firstName, lastName }
}
diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yaml
index c21c9d09..82d06fea 100755
--- a/environment/environment.dist.yaml
+++ b/environment/environment.dist.yaml
@@ -115,18 +115,22 @@ auth:
ldap:
# e.g: [ldap://localhost:389, ldaps://localhost:636] (array required)
servers: []
- # baseDN: distinguished name, e.g. (ou=people,dc=ldap,dc=sync-in,dc=com)
+ # baseDN: distinguished name ( e.g.ou=people,dc=ldap,dc=sync-in,dc=com)
baseDN:
# filter, e.g: (acl=admin)
filter:
- # login attribute: `uid` or `mail`
- # default: uid
- loginAttribute:
+ attributes:
+ # login attribute (e.g. `uid` | `sAMAccountName` | `userPrincipalName` | `userid`)
+ # default: `uid`
+ login: uid
+ # email attribute: `mail` or `email`
+ # default: `mail`
+ email: mail
applications:
files:
# required
dataPath: /home/sync-in
- # default: `5368709120` (5 GB)
+ # default: 5368709120 (5 GB)
maxUploadSize: 5368709120
# Show files starting with a dot in the file explorer
# default: false
@@ -137,7 +141,7 @@ applications:
enabled: false
# for an external server (e.g., https://onlyoffice.domain.com), remember the url must be accessible from browser !
# if externalServer is empty (case of official docker compose), we use the local instance
- # default: `null`
+ # default: null
externalServer:
# secret used for jwt tokens, it must be the same on the onlyoffice server
# required