-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
ldap.ts
407 lines (339 loc) · 10.2 KB
/
ldap.ts
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
import { Router } from 'express';
import ldap, {
Client,
Error,
EqualityFilter,
SearchCallbackResponse,
SearchEntry,
InappropriateAuthenticationError,
InvalidCredentialsError,
InsufficientAccessRightsError,
OperationsError,
} from 'ldapjs';
import ms from 'ms';
import Joi from 'joi';
import { AuthDriver } from '../auth';
import { AuthDriverOptions, User, SessionData } from '../../types';
import {
InvalidCredentialsException,
InvalidPayloadException,
ServiceUnavailableException,
InvalidConfigException,
} from '../../exceptions';
import { AuthenticationService, UsersService } from '../../services';
import asyncHandler from '../../utils/async-handler';
import env from '../../env';
import { respond } from '../../middleware/respond';
import logger from '../../logger';
interface UserInfo {
firstName?: string;
lastName?: string;
email?: string;
userAccountControl: number;
}
// 0x2: ACCOUNTDISABLE
// 0x10: LOCKOUT
// 0x800000: PASSWORD_EXPIRED
const INVALID_ACCOUNT_FLAGS = 0x800012;
export class LDAPAuthDriver extends AuthDriver {
bindClient: Client;
usersService: UsersService;
config: Record<string, any>;
constructor(options: AuthDriverOptions, config: Record<string, any>) {
super(options, config);
const { bindDn, bindPassword, userDn, provider, clientUrl } = config;
if (!bindDn || !bindPassword || !userDn || !provider || (!clientUrl && !config.client?.socketPath)) {
throw new InvalidConfigException('Invalid provider config', { provider });
}
const clientConfig = typeof config.client === 'object' ? config.client : {};
this.bindClient = ldap.createClient({ url: clientUrl, reconnect: true, ...clientConfig });
this.bindClient.on('error', (err: Error) => {
logger.warn(err);
});
this.usersService = new UsersService({ knex: this.knex, schema: this.schema });
this.config = config;
}
private async validateBindClient(): Promise<void> {
const { bindDn, bindPassword, provider } = this.config;
return new Promise((resolve, reject) => {
// Healthcheck bind user
this.bindClient.search(bindDn, {}, (err: Error | null, res: SearchCallbackResponse) => {
if (err) {
reject(handleError(err));
return;
}
res.on('searchEntry', () => {
resolve();
});
res.on('error', (err: Error) => {
if (!(err instanceof OperationsError)) {
reject(handleError(err));
return;
}
// Rebind on OperationsError
this.bindClient.bind(bindDn, bindPassword, (err: Error | null) => {
if (err) {
const error = handleError(err);
if (error instanceof InvalidCredentialsException) {
reject(new InvalidConfigException('Invalid bind user', { provider }));
} else {
reject(error);
}
} else {
resolve();
}
});
});
});
});
}
private async fetchUserDn(identifier: string): Promise<string | undefined> {
const { userDn, userAttribute, userScope } = this.config;
return new Promise((resolve, reject) => {
// Search for the user in LDAP by attribute
this.bindClient.search(
userDn,
{
filter: new EqualityFilter({ attribute: userAttribute, value: identifier }),
scope: userScope ?? 'one',
},
(err: Error | null, res: SearchCallbackResponse) => {
if (err) {
reject(handleError(err));
return;
}
res.on('searchEntry', ({ object }: SearchEntry) => {
resolve(object.dn.toLowerCase());
});
res.on('error', (err: Error) => {
reject(handleError(err));
});
res.on('end', () => {
resolve(undefined);
});
}
);
});
}
private async fetchUserInfo(userDn: string): Promise<UserInfo | undefined> {
const { mailAttribute } = this.config;
return new Promise((resolve, reject) => {
// Fetch user info in LDAP by domain component
this.bindClient.search(
userDn,
{ attributes: ['givenName', 'sn', mailAttribute ?? 'mail', 'userAccountControl'] },
(err: Error | null, res: SearchCallbackResponse) => {
if (err) {
reject(handleError(err));
return;
}
res.on('searchEntry', ({ object }: SearchEntry) => {
const email = object[mailAttribute ?? 'mail'];
const user = {
firstName: typeof object.givenName === 'object' ? object.givenName[0] : object.givenName,
lastName: typeof object.sn === 'object' ? object.sn[0] : object.sn,
email: typeof email === 'object' ? email[0] : email,
userAccountControl:
typeof object.userAccountControl === 'object'
? Number(object.userAccountControl[0])
: Number(object.userAccountControl),
};
resolve(user);
});
res.on('error', (err: Error) => {
reject(handleError(err));
});
res.on('end', () => {
resolve(undefined);
});
}
);
});
}
private async fetchUserGroups(userDn: string): Promise<string[]> {
const { groupDn, groupAttribute, groupScope } = this.config;
if (!groupDn) {
return Promise.resolve([]);
}
return new Promise((resolve, reject) => {
let userGroups: string[] = [];
// Search for the user info in LDAP by group attribute
this.bindClient.search(
groupDn,
{
attributes: ['cn'],
filter: new EqualityFilter({ attribute: groupAttribute, value: userDn }),
scope: groupScope ?? 'one',
},
(err: Error | null, res: SearchCallbackResponse) => {
if (err) {
reject(handleError(err));
return;
}
res.on('searchEntry', ({ object }: SearchEntry) => {
if (typeof object.cn === 'object') {
userGroups = [...userGroups, ...object.cn];
} else if (object.cn) {
userGroups.push(object.cn);
}
});
res.on('error', (err: Error) => {
reject(handleError(err));
});
res.on('end', () => {
resolve(userGroups);
});
}
);
});
}
private async fetchUserId(userDn: string): Promise<string | undefined> {
const user = await this.knex
.select('id')
.from('directus_users')
.orWhereRaw('LOWER(??) = ?', ['external_identifier', userDn.toLowerCase()])
.first();
return user?.id;
}
async getUserID(payload: Record<string, any>): Promise<string> {
if (!payload.identifier) {
throw new InvalidCredentialsException();
}
await this.validateBindClient();
const userDn = await this.fetchUserDn(payload.identifier);
if (!userDn) {
throw new InvalidCredentialsException();
}
const userId = await this.fetchUserId(userDn);
const userGroups = await this.fetchUserGroups(userDn);
let userRole;
if (userGroups.length) {
userRole = await this.knex
.select('id')
.from('directus_roles')
.whereRaw(`LOWER(??) IN (${userGroups.map(() => '?')})`, [
'name',
...userGroups.map((group) => group.toLowerCase()),
])
.first();
}
if (userId) {
await this.usersService.updateOne(userId, { role: userRole?.id ?? null });
return userId;
}
const userInfo = await this.fetchUserInfo(userDn);
if (!userInfo) {
throw new InvalidCredentialsException();
}
await this.usersService.createOne({
provider: this.config.provider,
first_name: userInfo.firstName,
last_name: userInfo.lastName,
email: userInfo.email,
external_identifier: userDn,
role: userRole?.id,
});
return (await this.fetchUserId(userDn)) as string;
}
async verify(user: User, password?: string): Promise<void> {
if (!user.external_identifier || !password) {
throw new InvalidCredentialsException();
}
return new Promise((resolve, reject) => {
const clientConfig = typeof this.config.client === 'object' ? this.config.client : {};
const client = ldap.createClient({
url: this.config.clientUrl,
...clientConfig,
reconnect: false,
});
client.on('error', (err: Error) => {
reject(handleError(err));
});
client.bind(user.external_identifier!, password, (err: Error | null) => {
if (err) {
reject(handleError(err));
} else {
resolve();
}
client.destroy();
});
});
}
async login(user: User, payload: Record<string, any>): Promise<SessionData> {
await this.verify(user, payload.password);
return null;
}
async refresh(user: User): Promise<SessionData> {
await this.validateBindClient();
const userInfo = await this.fetchUserInfo(user.external_identifier!);
if (userInfo?.userAccountControl && userInfo.userAccountControl & INVALID_ACCOUNT_FLAGS) {
throw new InvalidCredentialsException();
}
return null;
}
}
const handleError = (e: Error) => {
if (
e instanceof InappropriateAuthenticationError ||
e instanceof InvalidCredentialsError ||
e instanceof InsufficientAccessRightsError
) {
return new InvalidCredentialsException();
}
return new ServiceUnavailableException('Service returned unexpected error', {
service: 'ldap',
message: e.message,
});
};
export function createLDAPAuthRouter(provider: string): Router {
const router = Router();
const loginSchema = Joi.object({
identifier: Joi.string().required(),
password: Joi.string().required(),
mode: Joi.string().valid('cookie', 'json'),
otp: Joi.string(),
}).unknown();
router.post(
'/',
asyncHandler(async (req, res, next) => {
const accountability = {
ip: req.ip,
userAgent: req.get('user-agent'),
role: null,
};
const authenticationService = new AuthenticationService({
accountability: accountability,
schema: req.schema,
});
const { error } = loginSchema.validate(req.body);
if (error) {
throw new InvalidPayloadException(error.message);
}
const mode = req.body.mode || 'json';
const { accessToken, refreshToken, expires } = await authenticationService.login(
provider,
req.body,
req.body?.otp
);
const payload = {
data: { access_token: accessToken, expires },
} as Record<string, Record<string, any>>;
if (mode === 'json') {
payload.data.refresh_token = refreshToken;
}
if (mode === 'cookie') {
res.cookie(env.REFRESH_TOKEN_COOKIE_NAME, refreshToken, {
httpOnly: true,
domain: env.REFRESH_TOKEN_COOKIE_DOMAIN,
maxAge: ms(env.REFRESH_TOKEN_TTL as string),
secure: env.REFRESH_TOKEN_COOKIE_SECURE ?? false,
sameSite: (env.REFRESH_TOKEN_COOKIE_SAME_SITE as 'lax' | 'strict' | 'none') || 'strict',
});
}
res.locals.payload = payload;
return next();
}),
respond
);
return router;
}