-
-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathauth-provider-ldap.service.spec.ts
More file actions
629 lines (536 loc) · 24.5 KB
/
Copy pathauth-provider-ldap.service.spec.ts
File metadata and controls
629 lines (536 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import { Test, TestingModule } from '@nestjs/testing'
import { Mocked } from 'jest-mock'
import { Client, InvalidCredentialsError } from 'ldapts'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { CONNECT_ERROR_CODE } from '../../../app.constants'
import { USER_PERMISSION, USER_ROLE } from '../../../applications/users/constants/user'
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 * as commonFunctions from '../../../common/functions'
import { configuration } from '../../../configuration/config.environment'
import { DEFAULT_STORAGE_QUOTA_FIELD } from '../auth-providers.constants'
import type { AuthProviderLDAPConfig } from './auth-ldap.config'
import { LDAP_COMMON_ATTR, LDAP_LOGIN_ATTR } from './auth-ldap.constants'
import { AuthProviderLDAP } from './auth-provider-ldap.service'
jest.mock('ldapts', () => {
const actual = jest.requireActual('ldapts')
const mockClientInstance = {
bind: jest.fn(),
search: jest.fn(),
unbind: jest.fn()
}
const Client = jest.fn().mockImplementation(() => mockClientInstance)
return { ...actual, Client }
})
const buildUser = (overrides: Partial<UserModel> = {}) =>
({
id: 0,
login: 'john',
email: 'old@example.org',
password: 'hashed',
role: USER_ROLE.USER,
isGuest: false,
isActive: true,
isAdmin: false,
makePaths: jest.fn().mockResolvedValue(undefined),
setFullName: jest.fn(),
...overrides
}) as any
const ldapClient = {
bind: jest.fn(),
search: jest.fn(),
unbind: jest.fn()
}
;(Client as Mocked<any>).mockImplementation(() => ldapClient)
describe(AuthProviderLDAP.name, () => {
let authProviderLDAP: AuthProviderLDAP
let usersManager: Mocked<UsersManager>
let adminUsersManager: Mocked<AdminUsersManager>
type LdapConfigOverrides = Omit<Partial<AuthProviderLDAPConfig>, 'attributes' | 'options'> & {
attributes?: Partial<AuthProviderLDAPConfig['attributes']>
options?: Partial<AuthProviderLDAPConfig['options']>
}
const setLdapConfig = (overrides: LdapConfigOverrides = {}) => {
const base: AuthProviderLDAPConfig = {
servers: ['ldap://localhost:389'],
attributes: { login: LDAP_LOGIN_ATTR.UID, email: LDAP_COMMON_ATTR.MAIL, storageQuota: DEFAULT_STORAGE_QUOTA_FIELD },
baseDN: 'ou=people,dc=example,dc=org',
filter: '',
options: {
autoCreateUser: true,
autoCreatePermissions: [],
enablePasswordAuthFallback: true
}
}
const next: AuthProviderLDAPConfig = {
...base,
...overrides,
attributes: { ...base.attributes, ...(overrides.attributes || {}) },
options: { ...base.options, ...(overrides.options || {}) }
}
configuration.auth.ldap = next
;(authProviderLDAP as any).ldapConfig = next
;(authProviderLDAP as any).isAD = [LDAP_LOGIN_ATTR.SAM, LDAP_LOGIN_ATTR.UPN].includes(next.attributes.login)
;(authProviderLDAP as any).hasServiceBind = Boolean(next.serviceBindDN && next.serviceBindPassword)
;(authProviderLDAP as any).requestedAttributes = Array.from(
new Set([...Object.values(LDAP_LOGIN_ATTR), ...Object.values(LDAP_COMMON_ATTR), next.attributes.email, next.attributes.storageQuota])
)
;(authProviderLDAP as any).clientOptionsPromise = (authProviderLDAP as any).buildClientOptions()
}
const mockBindResolve = () => {
ldapClient.bind.mockResolvedValue(undefined)
ldapClient.unbind.mockResolvedValue(undefined)
}
const mockBindRejectInvalid = (message = 'invalid') => {
ldapClient.bind.mockRejectedValue(new InvalidCredentialsError(message))
ldapClient.unbind.mockResolvedValue(undefined)
}
const mockSearchEntries = (entries: any[]) => {
ldapClient.search.mockResolvedValue({ searchEntries: entries })
}
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthProviderLDAP,
{
provide: UsersManager,
useValue: {
findUser: jest.fn(),
logUser: jest.fn(),
updateAccesses: jest.fn().mockResolvedValue(undefined),
validateAppPassword: jest.fn(),
fromUserId: jest.fn()
}
},
{
provide: AdminUsersManager,
useValue: {
createUserOrGuest: jest.fn(),
updateUserOrGuest: jest.fn()
}
}
]
}).compile()
module.useLogger(['fatal'])
authProviderLDAP = module.get<AuthProviderLDAP>(AuthProviderLDAP)
adminUsersManager = module.get<Mocked<AdminUsersManager>>(AdminUsersManager)
usersManager = module.get<Mocked<UsersManager>>(UsersManager)
})
beforeEach(() => {
jest.clearAllMocks()
setLdapConfig()
usersManager.updateAccesses.mockResolvedValue(undefined)
})
afterEach(() => {
jest.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)
const dbAuthResult: any = { ...guestUser, token: 'jwt' }
usersManager.logUser.mockResolvedValue(dbAuthResult)
const res = await authProviderLDAP.validateUser('guest1', 'pass', '127.0.0.1')
expect(res).toEqual(dbAuthResult)
expect(usersManager.logUser).toHaveBeenCalledWith(guestUser, 'pass', '127.0.0.1', undefined)
expect(Client).not.toHaveBeenCalled()
})
it('should bypass LDAP when scope is provided', async () => {
const user = buildUser({ id: 12 })
usersManager.findUser.mockResolvedValue(user)
usersManager.logUser.mockResolvedValue(user)
const res = await authProviderLDAP.validateUser('john', 'app-password', '10.0.0.2', 'webdav' as any)
expect(res).toBe(user)
expect(usersManager.logUser).toHaveBeenCalledWith(user, 'app-password', '10.0.0.2', 'webdav')
expect(Client).not.toHaveBeenCalled()
})
it('should throw FORBIDDEN for locked account', async () => {
usersManager.findUser.mockResolvedValue({ login: 'john', isGuest: false, isActive: false } as UserModel)
const loggerErrorSpy = jest.spyOn(authProviderLDAP['logger'], 'error').mockImplementation(() => undefined as any)
await expect(authProviderLDAP.validateUser('john', 'pwd')).rejects.toThrow(/account locked/i)
expect(loggerErrorSpy).toHaveBeenCalled()
})
it('should return null on invalid LDAP credentials without fallback', async () => {
const existingUser: any = buildUser({ id: 1 })
usersManager.findUser.mockResolvedValue(existingUser)
mockBindRejectInvalid('invalid credentials')
const res = await authProviderLDAP.validateUser('john', 'badpwd', '10.0.0.1')
expect(res).toBeNull()
expect(usersManager.logUser).not.toHaveBeenCalled()
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 () => {
const existingUser: any = buildUser({ id: 2 })
usersManager.findUser.mockResolvedValue(existingUser)
usersManager.logUser.mockResolvedValue(existingUser)
const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
ldapClient.bind.mockRejectedValue({ errors: [err] })
ldapClient.unbind.mockResolvedValue(undefined)
const res = await authProviderLDAP.validateUser('john', 'pwd', '10.0.0.3')
expect(res).toBe(existingUser)
expect(usersManager.logUser).toHaveBeenCalledWith(existingUser, 'pwd', '10.0.0.3')
})
it('should throw SERVICE_UNAVAILABLE when LDAP is unavailable and fallback is disabled', async () => {
setLdapConfig({ options: { enablePasswordAuthFallback: false } })
const existingUser: any = buildUser({ id: 3 })
usersManager.findUser.mockResolvedValue(existingUser)
const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
ldapClient.bind.mockRejectedValue({ errors: [err] })
ldapClient.unbind.mockResolvedValue(undefined)
await expect(authProviderLDAP.validateUser('john', 'pwd')).rejects.toThrow(/authentication service error/i)
})
it('should allow admin local fallback when LDAP is unavailable even if fallback is disabled', async () => {
setLdapConfig({ options: { enablePasswordAuthFallback: false } })
const existingUser: any = buildUser({ id: 4, isAdmin: true })
usersManager.findUser.mockResolvedValue(existingUser)
usersManager.logUser.mockResolvedValue(existingUser)
const err = Object.assign(new Error('connect ECONNREFUSED'), { code: Array.from(CONNECT_ERROR_CODE)[0] })
ldapClient.bind.mockRejectedValue({ errors: [err] })
ldapClient.unbind.mockResolvedValue(undefined)
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(res).toBe(existingUser)
expect(usersManager.logUser).toHaveBeenCalledWith(existingUser, 'pwd', undefined)
})
it('should return null when LDAP entry lacks required fields', async () => {
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
mockSearchEntries([{ uid: 'jane', cn: 'Jane Doe', mail: undefined }])
const loggerErrorSpy = jest.spyOn(authProviderLDAP['logger'], 'error').mockImplementation(() => undefined as any)
const res = await authProviderLDAP.validateUser('jane', 'pwd')
expect(res).toBeNull()
expect(adminUsersManager.createUserOrGuest).not.toHaveBeenCalled()
expect(loggerErrorSpy).toHaveBeenCalled()
})
it('should throw UNAUTHORIZED when autoCreateUser is disabled', async () => {
setLdapConfig({ options: { autoCreateUser: false } })
usersManager.findUser.mockResolvedValue(null)
const checkAuthSpy = jest.spyOn<any, any>(authProviderLDAP as any, 'checkAuth').mockResolvedValue({
uid: 'john',
mail: 'john@example.org'
})
await expect(authProviderLDAP.validateUser('john', 'pwd')).rejects.toThrow(/user not found/i)
checkAuthSpy.mockRestore()
})
it('should create a new admin user with permissions and name parsed from LDAP', async () => {
setLdapConfig({
options: {
adminGroup: 'Admins',
autoCreatePermissions: [USER_PERMISSION.PERSONAL_SPACE, USER_PERMISSION.WEBDAV]
}
})
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
mockSearchEntries([
{
uid: 'john',
givenName: 'John',
sn: 'Doe',
mail: 'john@example.org',
memberOf: ['CN=Admins,OU=Groups,DC=example,DC=org']
}
])
const createdUser: any = { id: 2, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
usersManager.fromUserId.mockResolvedValue(createdUser)
const res = await authProviderLDAP.validateUser('john', 'pwd', '192.168.1.10')
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
{
login: 'john',
email: 'john@example.org',
password: 'pwd',
role: USER_ROLE.ADMINISTRATOR,
firstName: 'John',
lastName: 'Doe',
permissions: 'personal_space,webdav_access'
},
USER_ROLE.ADMINISTRATOR
)
expect(res).toBe(createdUser)
expect(usersManager.updateAccesses).toHaveBeenCalledWith(createdUser, '192.168.1.10', true)
})
it('should handle LDAP storage quota mapping cases', async () => {
jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(true)
const scenarios = [
{
mode: 'create',
entry: { uid: 'john', mail: 'john@example.org', quotaBytes: '2048' },
expectedQuota: 2048
},
{
mode: 'create',
entry: { uid: 'john', mail: 'john@example.org', quotaBytes: '0' },
expectedQuota: null
},
{
mode: 'update',
entry: { uid: 'john', mail: 'john@example.org' },
expectedUpdate: false
},
{
mode: 'update',
entry: { uid: 'john', mail: 'john@example.org', quotaBytes: null },
expectedUpdate: true,
expectedQuota: null
},
{
mode: 'update',
entry: { uid: 'john', mail: 'john@example.org', quotaBytes: 'invalid' },
expectedUpdate: false
},
{
mode: 'update',
entry: { uid: 'john', mail: 'john@example.org', quotaBytes: '9007199254740992' },
expectedUpdate: false
}
] as const
setLdapConfig({ attributes: { storageQuota: 'quotaBytes' } })
for (const [index, scenario] of scenarios.entries()) {
jest.clearAllMocks()
mockBindResolve()
mockSearchEntries([scenario.entry])
if (scenario.mode === 'create') {
const createdUser: any = { id: 22 + index, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
usersManager.findUser.mockResolvedValue(null)
adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
usersManager.fromUserId.mockResolvedValue(createdUser)
await authProviderLDAP.validateUser('john', 'pwd')
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
expect.objectContaining({ storageQuota: scenario.expectedQuota }),
USER_ROLE.USER
)
continue
}
const existingUser: any = buildUser({ id: 60 + index, email: 'john@example.org', firstName: '', lastName: '', storageQuota: 4096 })
usersManager.findUser.mockResolvedValue(existingUser)
await authProviderLDAP.validateUser('john', 'pwd')
if (scenario.expectedUpdate) {
expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
existingUser.id,
expect.objectContaining({ storageQuota: scenario.expectedQuota })
)
} else {
expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
}
}
})
it('should accept adminGroup as full DN', async () => {
setLdapConfig({
options: {
adminGroup: 'CN=Admins,OU=Groups,DC=example,DC=org'
}
})
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
mockSearchEntries([
{
uid: 'john',
givenName: 'John',
sn: 'Doe',
mail: 'john@example.org',
memberOf: ['CN=Admins,OU=Groups,DC=example,DC=org']
}
])
const createdUser: any = { id: 9, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
usersManager.fromUserId.mockResolvedValue(createdUser)
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
expect.objectContaining({ role: USER_ROLE.ADMINISTRATOR }),
USER_ROLE.ADMINISTRATOR
)
expect(res).toBe(createdUser)
})
it('should use groupOfNames to detect admin membership when memberOf is missing', async () => {
setLdapConfig({ options: { adminGroup: 'Admins' } })
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
ldapClient.search
.mockResolvedValueOnce({
searchEntries: [
{
uid: 'john',
cn: 'John Doe',
mail: 'john@example.org',
dn: 'uid=john,ou=people,dc=example,dc=org'
}
]
})
.mockResolvedValueOnce({ searchEntries: [{ cn: 'Admins' }] })
const createdUser: any = { id: 3, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
usersManager.fromUserId.mockResolvedValue(createdUser)
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
expect.objectContaining({ role: USER_ROLE.ADMINISTRATOR }),
USER_ROLE.ADMINISTRATOR
)
expect(res).toBe(createdUser)
})
it('should use service bind for LDAP searches when configured', async () => {
setLdapConfig({
serviceBindDN: 'cn=svc,dc=example,dc=org',
serviceBindPassword: 'secret'
})
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
ldapClient.search.mockResolvedValueOnce({
searchEntries: [{ uid: 'john', cn: 'John Doe', mail: 'john@example.org', dn: 'uid=john,ou=people,dc=example,dc=org' }]
})
const createdUser: any = { id: 8, login: 'john', isGuest: false, isActive: true, makePaths: jest.fn() }
adminUsersManager.createUserOrGuest.mockResolvedValue(createdUser)
usersManager.fromUserId.mockResolvedValue(createdUser)
await authProviderLDAP.validateUser('john', 'pwd')
expect(ldapClient.bind).toHaveBeenCalledWith('cn=svc,dc=example,dc=org', 'secret')
expect(ldapClient.bind).toHaveBeenCalledWith('uid=john,ou=people,dc=example,dc=org', 'pwd')
})
it('should return null when service bind is set but user DN is not found', async () => {
setLdapConfig({
serviceBindDN: 'cn=svc,dc=example,dc=org',
serviceBindPassword: 'secret'
})
usersManager.findUser.mockResolvedValue(null)
mockBindResolve()
ldapClient.search.mockResolvedValueOnce({ searchEntries: [] })
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(res).toBeNull()
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')
})
it('should return null when user bind fails after service bind', async () => {
setLdapConfig({
serviceBindDN: 'cn=svc,dc=example,dc=org',
serviceBindPassword: 'secret'
})
usersManager.findUser.mockResolvedValue(null)
ldapClient.unbind.mockResolvedValue(undefined)
ldapClient.bind.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new InvalidCredentialsError('invalid credentials'))
ldapClient.search.mockResolvedValueOnce({
searchEntries: [{ dn: 'uid=john,ou=people,dc=example,dc=org', cn: 'John Doe' }]
})
const res = await authProviderLDAP.validateUser('john', 'pwd')
expect(res).toBeNull()
expect(ldapClient.bind).toHaveBeenCalledWith('cn=svc,dc=example,dc=org', 'secret')
expect(ldapClient.bind).toHaveBeenCalledWith('uid=john,ou=people,dc=example,dc=org', 'pwd')
})
it('should keep admin role when adminGroup is not configured', async () => {
setLdapConfig({ options: { adminGroup: undefined } })
const existingUser: any = buildUser({ id: 5, role: USER_ROLE.ADMINISTRATOR })
usersManager.findUser.mockResolvedValue(existingUser)
mockBindResolve()
mockSearchEntries([{ uid: 'john', cn: 'John Doe', mail: 'john@example.org' }])
jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(true)
await authProviderLDAP.validateUser('john', 'pwd')
expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalled()
const updateArgs = adminUsersManager.updateUserOrGuest.mock.calls[0][1]
expect(updateArgs).toEqual(expect.objectContaining({ email: 'john@example.org' }))
expect(updateArgs).toEqual(expect.not.objectContaining({ role: expect.anything() }))
})
it('should update existing user and avoid reassigning password locally', async () => {
const existingUser: any = buildUser({ id: 6 })
usersManager.findUser.mockResolvedValue(existingUser)
mockBindResolve()
mockSearchEntries([{ uid: 'john', displayName: 'Jane Doe', mail: 'john@example.org' }])
const compareSpy = jest.spyOn(commonFunctions, 'comparePassword').mockResolvedValue(false)
const splitSpy = jest.spyOn(commonFunctions, 'splitFullName').mockReturnValue({ firstName: 'Jane', lastName: 'Doe' })
const res = await authProviderLDAP.validateUser('john', 'new-plain-password', '127.0.0.2')
expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
6,
expect.objectContaining({
email: 'john@example.org',
firstName: 'Jane',
lastName: 'Doe'
})
)
expect(existingUser.password).toBe('hashed')
expect(existingUser).toMatchObject({ email: 'john@example.org', firstName: 'Jane', lastName: 'Doe' })
expect(existingUser.setFullName).toHaveBeenCalledWith(true)
expect(usersManager.updateAccesses).toHaveBeenCalledWith(existingUser, '127.0.0.2', true)
expect(res).toBe(existingUser)
compareSpy.mockRestore()
splitSpy.mockRestore()
})
it('should throw FORBIDDEN when LDAP login does not match user login', async () => {
const existingUser: any = buildUser({ id: 7, login: 'john' })
usersManager.findUser.mockResolvedValue(existingUser)
mockBindResolve()
mockSearchEntries([{ uid: 'jane', cn: 'Jane Doe', mail: 'jane@example.org' }])
await expect(authProviderLDAP.validateUser('john', 'pwd')).rejects.toThrow(/account matching error/i)
})
it('should build LDAP logins and filters for AD and standard LDAP', () => {
setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.UPN }, upnSuffix: 'sync-in.com', filter: '(memberOf=cn=staff)' })
const adLogin = (authProviderLDAP as any).buildLdapLogin('john')
expect(adLogin).toBe('john@sync-in.com')
const adFilter = (authProviderLDAP as any).buildUserFilter('SYNC-IN\\john', '(memberOf=cn=staff)')
expect(adFilter).toContain('(sAMAccountName=john)')
expect(adFilter).toContain('(userPrincipalName=john)')
expect(adFilter).toContain('(mail=john)')
expect(adFilter).toContain('(memberOf=cn=staff)')
setLdapConfig({ attributes: { login: LDAP_LOGIN_ATTR.UID }, filter: '(department=IT)' })
const ldapFilter = (authProviderLDAP as any).buildUserFilter('john', '(department=IT)')
expect(ldapFilter).toContain('(uid=john)')
expect(ldapFilter).toContain('(cn=john)')
expect(ldapFilter).toContain('(mail=john)')
expect(ldapFilter).toContain('(department=IT)')
})
it('should normalize LDAP entries for memberOf and array attributes', () => {
const entry = {
uid: ['john'],
mail: ['john@example.org', 'john2@example.org'],
memberOf: ['CN=Admins,OU=Groups,DC=example,DC=org', 'CN=Staff,OU=Groups,DC=example,DC=org']
}
const normalized = (authProviderLDAP as any).convertToLdapUserEntry(entry)
expect(normalized.uid).toBe('john')
expect(normalized.mail).toBe('john@example.org')
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')
await writeFile(caPath, 'CA_PEM')
setLdapConfig({ tlsOptions: { ca: [caPath, 'INLINE_CA'] } })
const initialClientOptions = await (authProviderLDAP as any).clientOptionsPromise
expect(initialClientOptions.tlsOptions).toEqual({
ca: ['CA_PEM', 'INLINE_CA']
})
const initialCa = initialClientOptions.tlsOptions.ca
;(authProviderLDAP as any).ldapConfig.tlsOptions.ca = 'CHANGED_INLINE'
expect((await (authProviderLDAP as any).clientOptionsPromise).tlsOptions.ca).toBe(initialCa)
await rm(tmpPath, { recursive: true, force: true })
})
it('should warn and fallback when ca path is not readable', async () => {
const warnSpy = jest.spyOn(authProviderLDAP['logger'], 'warn').mockImplementation(() => undefined)
const unreadableCaPath = '/definitely/missing/ca.pem'
const ca = await (authProviderLDAP as any).readTlsCa(unreadableCaPath)
expect(ca).toBe(unreadableCaPath)
expect(warnSpy).toHaveBeenCalledWith(
expect.objectContaining({
msg: expect.stringContaining('unable to read ca path, assume inline PEM content')
})
)
})
})