-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathGoogleLDAPAuth.ts
More file actions
185 lines (156 loc) · 4.72 KB
/
GoogleLDAPAuth.ts
File metadata and controls
185 lines (156 loc) · 4.72 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
import ldapjs, { ClientOptions } from 'ldapjs';
import * as tls from 'tls';
import * as fs from 'fs';
import { IAuthentication } from '../interfaces/Authentication.js';
import { Logger } from '../logger/Logger.js';
const usernameFields = ['posixUid', 'mail'];
// TLS:
// https://github.com/ldapjs/node-ldapjs/issues/307
interface IGoogleLDAPAuthOptions {
/** base DN
* e.g. 'dc=hokify,dc=com', */
base: string;
searchBase?: string; // default ou=users,{{base}}
tls: {
keyFile: string;
certFile: string;
};
/** tls options
* e.g. {
key: fs.readFileSync('ldap.gsuite.key'),
cert: fs.readFileSync('ldap.gsuite.crt')
} */
tlsOptions?: tls.TlsOptions;
}
export class GoogleLDAPAuth implements IAuthentication {
private logger = new Logger('GoogleLDAPAuth');
private base: string;
private config: ClientOptions;
private searchBase: string;
private dnsFetch: Promise<{ [key: string]: string }> | undefined;
constructor(config: IGoogleLDAPAuthOptions) {
this.base = config.base;
this.searchBase = config.searchBase || `ou=users,${this.base}`;
const tlsOptions = {
key: fs.readFileSync(config.tls.keyFile),
cert: fs.readFileSync(config.tls.certFile),
servername: 'ldap.google.com',
...config.tlsOptions,
};
this.config = {
url: 'ldaps://ldap.google.com:636',
tlsOptions,
};
this.dnsFetch = this.fetchDNs();
this.dnsFetch.catch((err) => {
this.logger.error('fatal error google ldap auth, cannot fetch DNs', err);
});
}
private async fetchDNs(): Promise<{ [key: string]: string }> {
try {
const dns: { [key: string]: string } = {};
const dnResult = await new Promise<{ [key: string]: string }>((resolve, reject) => {
const ldapDNClient = ldapjs.createClient(this.config).on('error', (error) => {
this.logger.error('Error in ldap', error);
reject(error);
});
ldapDNClient.search(
this.searchBase,
{
scope: 'sub',
// only select required attributes
attributes: [...usernameFields, 'dn'],
},
(err, res) => {
if (err) {
reject(err);
return;
}
res.on('searchEntry', (entry) => {
// this.logger.debug('entry: ' + JSON.stringify(entry.object));
usernameFields.forEach((field) => {
const index = entry.object[field] as string;
dns[index] = entry.object.dn;
});
});
res.on('searchReference', (referral) => {
this.logger.debug(`referral: ${referral.uris.join()}`);
});
res.on('error', (ldapErr) => {
this.logger.error(`error: ${JSON.stringify(ldapErr)}`);
reject(ldapErr);
});
res.on('end', (result) => {
this.logger.debug(`ldap status: ${result?.status}`);
// this.logger.debug('allValidDNsCache', this.allValidDNsCache);
resolve(dns);
});
}
);
});
setTimeout(() => {
this.dnsFetch = undefined;
}, 60 * 60 * 12 * 1000); // reset cache after 12h
return dnResult;
} catch (err) {
this.logger.error('dns fetch err', err);
// retry dns fetch next time
this.dnsFetch = undefined;
throw err;
}
}
async authenticate(
username: string,
password: string,
count = 0,
forceFetching = false
): Promise<boolean> {
/*
just a test for super slow google responses
await new Promise((resolve, reject) => {
setTimeout(resolve, 10000); // wait 10 seconds
})
*/
let dnsFetched = false;
if (!this.dnsFetch || forceFetching) {
this.logger.debug('fetching dns');
this.dnsFetch = this.fetchDNs();
dnsFetched = true;
}
const resolvedDNs = await this.dnsFetch;
if (count > 5) {
throw new Error('Failed to authenticate with LDAP!');
}
// const dn = ;
const dn = resolvedDNs[username];
if (!dn) {
if (!dnsFetched && !forceFetching) {
return this.authenticate(username, password, count, true);
}
// this.logger.this.logger.debug('this.allValidDNsCache', this.allValidDNsCache);
this.logger.error(`invalid username, not found in DN: ${username}`); // , this.allValidDNsCache);
return false;
}
const authResult: boolean = await new Promise((resolve, reject) => {
// we never unbding a client, therefore create a new client every time
const authClient = ldapjs.createClient(this.config);
authClient.bind(dn, password, (err, res) => {
if (err) {
if (err && (err as any).stack && (err as any).stack.includes(`ldap.google.com closed`)) {
count += 1;
// wait 1 second to give the ldap error handler time to reconnect
setTimeout(() => resolve(this.authenticate(dn, password)), 2000);
return;
}
resolve(false);
// this.logger.error('ldap error', err);
// reject(err);
}
if (res) resolve(res);
else reject();
authClient.unbind();
});
});
return authResult;
}
}