-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathindex.js
More file actions
673 lines (619 loc) · 17.5 KB
/
index.js
File metadata and controls
673 lines (619 loc) · 17.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
const assert = require('assert')
const ldapts = require('ldapts')
// escape the , in CN in DN
function _ldapEscapeDN(s) {
let ret = ''
let comaPositions = []
let done = false
let countEq = 0
for (let i = 0; !done && i < s.length; i++) {
switch (s[i]) {
case '\\':
// user already escapped, continue
i++
break
case ',':
if (countEq == 1) {
comaPositions.push(i)
}
break
case '=':
countEq++
if (countEq == 2) {
done = true
}
break
}
}
if (done) {
comaPositions.pop()
}
let lastIndex = 0
for (let i of comaPositions) {
ret += s.substring(lastIndex, i)
ret += '\\,'
lastIndex = i + 1
}
ret += s.substring(lastIndex)
return ret
}
const AUTH_RESULT_FAILURE = 0
const AUTH_RESULT_SUCCESS = 1
const AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND = -1
const AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS = -2
const AUTH_RESULT_FAILURE_CREDENTIAL_INVALID = -3
const AUTH_RESULT_FAILURE_UNCATEGORIZED = -4
class AuthenticationResult {
#authCode = AUTH_RESULT_FAILURE_UNCATEGORIZED
#identity
#user
#messages = []
#client
constructor(authCode, identity, user, messages, client) {
this.#authCode = authCode // one of the above constants
this.#identity = identity // identity supplied as string
this.#user = user // user object found on ldap server OR null
this.#messages = messages // authentication messages array, which contains server messages
this.#client = client // ldapClient instance
}
get code() {
return this.#authCode
}
get identity() {
return this.#identity
}
get messages() {
return this.#messages
}
get client() {
return this.#client
}
get user() {
return this.#user
}
}
const authenticationMessages = {
AUTH_RESULT_FAILURE: 'Authentication failed',
AUTH_RESULT_SUCCESS: 'Authentication successful',
AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND: 'Authentication identity not found',
AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS: 'Authentication identity ambiguous',
AUTH_RESULT_FAILURE_CREDENTIAL_INVALID: 'Invalid credentials',
AUTH_RESULT_FAILURE_UNCATEGORIZED: 'Uncategorized authentication failure',
}
// bind and return the ldap client
async function _ldapBind(dn, password, starttls, ldapOpts) {
// TODO: check if ldapts expects escaped dn or not (possible double escaping problems?)
dn = _ldapEscapeDN(dn)
ldapOpts.connectTimeout = ldapOpts.connectTimeout || 5000
// When using StartTLS, we need to exclude tlsOptions from the Client constructor
// and only pass them to the startTLS() method to avoid connection conflicts.
// According to ldapts documentation:
// - For LDAPS (ldaps://): pass tlsOptions to Client constructor
// - For StartTLS (ldap://): do NOT pass tlsOptions to Client constructor, only to startTLS()
// - For plain LDAP (ldap://): do NOT pass tlsOptions to Client constructor
let clientOpts = ldapOpts
const isLdaps = ldapOpts.url && ldapOpts.url.startsWith('ldaps://')
// Only pass tlsOptions to Client constructor if using ldaps:// protocol
// For ldap:// protocol (plain or StartTLS), exclude tlsOptions from constructor
if (!isLdaps && ldapOpts.tlsOptions) {
// Create a shallow copy of ldapOpts without tlsOptions for the Client constructor
const { tlsOptions, ...optsWithoutTls } = ldapOpts
clientOpts = optsWithoutTls
}
let client = new ldapts.Client(clientOpts)
if (starttls) {
await client.startTLS(ldapOpts.tlsOptions)
}
await client.bind(dn, password)
ldapOpts.log && ldapOpts.log.trace('bind success!')
return client
}
// search a user and return the object
async function _searchUser(
ldapClient,
searchBase,
usernameAttribute,
username,
attributes = null,
explicitBufferAttributes = null
) {
let filter = new ldapts.EqualityFilter({
attribute: usernameAttribute,
value: username,
})
let searchOptions = {
filter: filter,
scope: 'sub',
attributes: attributes,
}
if (attributes) {
searchOptions.attributes = attributes
}
if(explicitBufferAttributes) {
searchOptions.explicitBufferAttributes = explicitBufferAttributes
}
// TODO: we don't support reference yet
// If the server was able to locate the entry referred to by the baseObject
// but could not search one or more non-local entries,
// the server may return one or more SearchResultReference messages,
// each containing a reference to another set of servers for continuing the operation.
// referral.uris
const { searchEntries, searchReferences } = await ldapClient.search(
searchBase,
searchOptions
)
let user
if (
!searchEntries ||
searchEntries.length < 1 ||
!searchEntries[0] ||
!searchEntries[0].dn
) {
return new AuthenticationResult(
AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND],
ldapClient
)
} else {
if (searchEntries.length > 1) {
return new AuthenticationResult(
AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS],
ldapClient
)
}
user = searchEntries[0]
}
// when attribute endwith ;binary, ldapts returns Buffer, we convert them into base64 string
if (user != null && attributes != null) {
for (let attr of attributes) {
if (attr.endsWith(';binary') && Buffer.isBuffer(user[attr])) {
user[attr] = user[attr].toString('base64')
}
}
}
// when attribute is one of the explicitBufferAttributes, should convert to base64 string
if (user != null && explicitBufferAttributes != null) {
for (let attr of explicitBufferAttributes) {
if (Buffer.isBuffer(user[attr])) {
user[attr] = user[attr].toString('base64')
}
}
}
return new AuthenticationResult(
AUTH_RESULT_SUCCESS,
username,
user,
[authenticationMessages.AUTH_RESULT_SUCCESS],
ldapClient
)
}
// search a groups which user is member
async function _searchUserGroups(
ldapClient,
searchBase,
user,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn'
) {
// Below works, but prefer using ldapts Filter subclasses to build this search, so that correct escaping is done
// const filter = `(&(objectclass=${groupClass})(${groupMemberAttribute}=${user[groupMemberUserAttribute]}))`
const filter = new ldapts.AndFilter({
filters: [
new ldapts.EqualityFilter({
attribute: 'objectclass',
value: groupClass,
}),
new ldapts.EqualityFilter({
attribute: groupMemberAttribute,
value: user[groupMemberUserAttribute],
}),
],
})
const { searchEntries, searchReferences } = await ldapClient.search(
searchBase,
{
filter: filter,
scope: 'sub',
}
)
let groups
if (!searchEntries || searchEntries.length < 1) {
groups = []
} else {
groups = searchEntries
}
// ldapjs has group.objectName, ldapts does not have it. instead, use dn
// add objectName back for backward compatibility
for (let group of groups) {
if (typeof group.objectName === 'undefined') {
group.objectName = group.dn
}
}
return groups
}
async function authenticateWithAdmin(
adminDn,
adminPassword,
userSearchBase,
usernameAttribute,
username,
userPassword,
starttls,
ldapOpts,
groupsSearchBase,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn',
attributes = null,
explicitBufferAttributes = null
) {
let ldapAdminClient
try {
ldapAdminClient = await _ldapBind(
adminDn,
adminPassword,
starttls,
ldapOpts
)
} catch (error) {
if (ldapAdminClient && ldapAdminClient.isConnected) {
await ldapAdminClient.unbind()
}
return new AuthenticationResult(
AUTH_RESULT_FAILURE,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE, error.message || 'admin bind failed'],
ldapAdminClient
)
}
let searchResult = await _searchUser(
ldapAdminClient,
userSearchBase,
usernameAttribute,
username,
attributes,
explicitBufferAttributes
)
let user = searchResult.user
if (!user || !user.dn) {
ldapOpts.log &&
ldapOpts.log.trace(
`admin did not find user! (${usernameAttribute}=${username})`
)
await ldapAdminClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND],
ldapAdminClient
)
}
let userDn = user.dn
let ldapUserClient
try {
ldapUserClient = await _ldapBind(userDn, userPassword, starttls, ldapOpts)
} catch (error) {
if (ldapUserClient && ldapUserClient.isConnected) {
await ldapUserClient.unbind()
}
return new AuthenticationResult(
AUTH_RESULT_FAILURE_CREDENTIAL_INVALID,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE_CREDENTIAL_INVALID, error.message || 'invalid credentials'],
ldapAdminClient
)
}
if (groupsSearchBase && groupClass && groupMemberAttribute) {
let groups = await _searchUserGroups(
ldapAdminClient,
groupsSearchBase,
user,
groupClass,
groupMemberAttribute,
groupMemberUserAttribute
)
user.groups = groups
}
await ldapAdminClient.unbind()
await ldapUserClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_SUCCESS,
username,
user,
[authenticationMessages.AUTH_RESULT_SUCCESS],
ldapAdminClient
)
}
async function authenticateWithUser(
userDn,
userSearchBase,
usernameAttribute,
username,
userPassword,
starttls,
ldapOpts,
groupsSearchBase,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn',
attributes = null,
explicitBufferAttributes = null
) {
let ldapUserClient
try {
ldapUserClient = await _ldapBind(userDn, userPassword, starttls, ldapOpts)
} catch (error) {
if (ldapUserClient && ldapUserClient.isConnected) {
await ldapUserClient.unbind()
}
return new AuthenticationResult(
AUTH_RESULT_FAILURE,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE, error.message || 'user bind failed'],
ldapUserClient
)
}
if (!usernameAttribute || !userSearchBase) {
// if usernameAttribute is not provided, no user detail is needed.
await ldapUserClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_SUCCESS,
username,
{},
[authenticationMessages.AUTH_RESULT_SUCCESS],
ldapUserClient
)
}
let searchResult = await _searchUser(
ldapUserClient,
userSearchBase,
usernameAttribute,
username,
attributes,
explicitBufferAttributes
)
let user = searchResult.user
if (!user || !user.dn) {
ldapOpts.log &&
ldapOpts.log.trace(
`user logged in, but user details could not be found. (${usernameAttribute}=${username}). Probabaly wrong attribute or searchBase?`
)
await ldapUserClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_FAILURE,
username,
null,
[
authenticationMessages.AUTH_RESULT_FAILURE,
'user logged in, but user details could not be found. Probabaly usernameAttribute or userSearchBase is wrong?',
],
ldapUserClient
)
}
if (groupsSearchBase && groupClass && groupMemberAttribute) {
let groups = await _searchUserGroups(
ldapUserClient,
groupsSearchBase,
user,
groupClass,
groupMemberAttribute,
groupMemberUserAttribute
)
user.groups = groups
}
await ldapUserClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_SUCCESS,
username,
user,
[authenticationMessages.AUTH_RESULT_SUCCESS],
ldapUserClient
)
}
async function verifyUserExists(
adminDn,
adminPassword,
userSearchBase,
usernameAttribute,
username,
starttls,
ldapOpts,
groupsSearchBase,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn',
attributes = null,
explicitBufferAttributes = null
) {
let ldapAdminClient
try {
ldapAdminClient = await _ldapBind(
adminDn,
adminPassword,
starttls,
ldapOpts
)
} catch (error) {
if (ldapAdminClient && ldapAdminClient.isConnected) {
await ldapAdminClient.unbind()
}
return new AuthenticationResult(
AUTH_RESULT_FAILURE,
username,
null,
[authenticationMessages.AUTH_RESULT_FAILURE, error.message || 'admin bind failed'],
ldapAdminClient
)
}
let searchResult = await _searchUser(
ldapAdminClient,
userSearchBase,
usernameAttribute,
username,
attributes,
explicitBufferAttributes
)
let user = searchResult.user
if (!user || !user.dn) {
ldapOpts.log &&
ldapOpts.log.trace(
`admin did not find user! (${usernameAttribute}=${username})`
)
await ldapAdminClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND,
username,
null,
[
authenticationMessages.AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND,
'user not found or usernameAttribute is wrong'
],
ldapAdminClient
)
}
if (groupsSearchBase && groupClass && groupMemberAttribute) {
let groups = await _searchUserGroups(
ldapAdminClient,
groupsSearchBase,
user,
groupClass,
groupMemberAttribute,
groupMemberUserAttribute
)
user.groups = groups
}
await ldapAdminClient.unbind()
return new AuthenticationResult(
AUTH_RESULT_SUCCESS,
username,
user,
[authenticationMessages.AUTH_RESULT_SUCCESS],
ldapAdminClient
)
}
async function authenticate(options) {
const result = await authenticateResult(options)
if (result.code !== AUTH_RESULT_SUCCESS) {
throw new LdapAuthenticationError(
result.messages[result.messages.length - 1]
)
}
return result.user
}
async function authenticateResult(options) {
if (!options.userDn) {
assert(options.adminDn, 'Admin mode adminDn must be provided')
assert(options.adminPassword, 'Admin mode adminPassword must be provided')
assert(options.userSearchBase, 'Admin mode userSearchBase must be provided')
assert(
options.usernameAttribute,
'Admin mode usernameAttribute must be provided'
)
assert(options.username, 'Admin mode username must be provided')
} else {
assert(options.userDn, 'User mode userDn must be provided')
}
assert(
options.ldapOpts && options.ldapOpts.url,
'ldapOpts.url must be provided'
)
if (options.verifyUserExists) {
assert(options.adminDn, 'Admin mode adminDn must be provided')
assert(
options.adminPassword,
'adminDn and adminPassword must be both provided.'
)
return await verifyUserExists(
options.adminDn,
options.adminPassword,
options.userSearchBase,
options.usernameAttribute,
options.username,
options.starttls,
options.ldapOpts,
options.groupsSearchBase,
options.groupClass,
options.groupMemberAttribute,
options.groupMemberUserAttribute,
options.attributes,
options.explicitBufferAttributes
)
}
assert(options.userPassword, 'userPassword must be provided')
if (options.adminDn) {
assert(
options.adminPassword,
'adminDn and adminPassword must be both provided.'
)
return await authenticateWithAdmin(
options.adminDn,
options.adminPassword,
options.userSearchBase,
options.usernameAttribute,
options.username,
options.userPassword,
options.starttls,
options.ldapOpts,
options.groupsSearchBase,
options.groupClass,
options.groupMemberAttribute,
options.groupMemberUserAttribute,
options.attributes,
options.explicitBufferAttributes
)
}
assert(options.userDn, 'adminDn/adminPassword OR userDn must be provided')
return await authenticateWithUser(
options.userDn,
options.userSearchBase,
options.usernameAttribute,
options.username,
options.userPassword,
options.starttls,
options.ldapOpts,
options.groupsSearchBase,
options.groupClass,
options.groupMemberAttribute,
options.groupMemberUserAttribute,
options.attributes,
options.explicitBufferAttributes
)
}
class LdapAuthenticationError extends Error {
constructor(message) {
super(message)
// Ensure the name of this error is the same as the class name
this.name = this.constructor.name
// This clips the constructor invocation from the stack trace.
// It's not absolutely essential, but it does make the stack trace a little nicer.
// @see Node.js reference (bottom)
Error.captureStackTrace(this, this.constructor)
}
}
module.exports.AUTH_RESULT_FAILURE = AUTH_RESULT_FAILURE
module.exports.AUTH_RESULT_SUCCESS = AUTH_RESULT_SUCCESS
module.exports.AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND =
AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND
module.exports.AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS =
AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS
module.exports.AUTH_RESULT_FAILURE_CREDENTIAL_INVALID =
AUTH_RESULT_FAILURE_CREDENTIAL_INVALID
module.exports.AUTH_RESULT_FAILURE_UNCATEGORIZED =
AUTH_RESULT_FAILURE_UNCATEGORIZED
module.exports.AuthenticationResult = AuthenticationResult
module.exports.authenticate = authenticate
module.exports.authenticateResult = authenticateResult
module.exports.LdapAuthenticationError = LdapAuthenticationError
module.exports.exportForTesting = {
_ldapEscapeDN,
}