-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
429 lines (408 loc) · 18.2 KB
/
Copy pathindex.js
File metadata and controls
429 lines (408 loc) · 18.2 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
'use strict';
const Ajv = require('ajv/dist/jtd');
const fs = require('fs');
const undici = require('undici');
const {URL} = require('url');
let logger = {};
for (const level of ['debug', 'info', 'warn', 'error']) {
logger[level] = console[level].bind(console, 'ep_openid_connect:');
}
const defaultSettings = {
prohibited_usernames: ['admin', 'guest'],
scope: ['openid'],
user_properties: {},
};
let settings;
let oidcConfig = null;
// openid-client@6 is ESM-only, so it must be loaded with a dynamic import from
// this CommonJS module. The reference is cached after the first call.
let oidc = null;
const loadOidc = async () => {
if (oidc == null) oidc = await import('openid-client');
return oidc;
};
const validSettings = new Ajv().compile({
properties: {
base_url: {type: 'string'},
client_id: {type: 'string'},
client_secret: {type: 'string'},
},
optionalProperties: {
// Path to a PEM-encoded certificate authority bundle (or the PEM
// content itself, recognised by a leading `-----BEGIN`). Used to verify
// TLS connections to identity providers that present a certificate
// signed by a private/internal CA. Operators who control the Node
// process can equivalently set NODE_EXTRA_CA_CERTS — this option is for
// settings.json-driven deployments where touching the Node startup
// command isn't an option.
ca: {type: 'string'},
issuer: {type: 'string'},
issuer_metadata: {},
prohibited_usernames: {elements: {type: 'string'}},
scope: {elements: {type: 'string'}},
token_endpoint_auth_method: {enum: ['client_secret_basic', 'client_secret_post']},
user_properties: {values: {
optionalProperties: {
claim: {type: 'string'},
// `role` looks the named string up inside the `roles` claim's array
// value. Used by IdPs like Azure/Entra that surface role assignments
// via a single `roles` array claim instead of a dedicated claim per
// property. Set the property to `true` when the role is present.
role: {type: 'string'},
// `default` is assigned verbatim to `req.session.user[propName]`,
// so any JSON value (boolean for is_admin/readOnly/canCreate,
// number, string, …) is fine. Use the JTD empty form so we don't
// reject non-string defaults (#100).
default: {},
},
nullable: true,
}},
},
});
const ep = (endpoint) => `/ep_openid_connect/${endpoint}`;
const endpointUrl = (endpoint) => new URL(ep(endpoint).substr(1), settings.base_url).toString();
const callbackUrlFromRequest = (req) => {
const callbackUrl = new URL(endpointUrl('callback'));
const requestUrl = new URL(req.originalUrl || req.url, settings.base_url);
for (const [key, value] of requestUrl.searchParams) {
callbackUrl.searchParams.append(key, value);
}
return callbackUrl;
};
const validateSubClaim = (sub) => {
if (typeof sub !== 'string' || // 'sub' claim must exist as a string per OIDC spec.
sub === '' || // Empty string doesn't make sense.
sub === '__proto__' || // Prevent prototype pollution.
settings.prohibited_usernames.includes(sub)) {
throw new Error('invalid sub claim');
}
};
const isHttp = (urlString) => {
try {
return new URL(urlString).protocol === 'http:';
} catch (e) {
return false;
}
};
// Load a CA bundle from either a path or an inline PEM string. Returns the
// PEM content as a string, or `null` for an empty/missing setting.
// Exported for unit testing.
const loadCaBundle = (caSetting) => {
if (typeof caSetting !== 'string' || !caSetting) return null;
if (caSetting.startsWith('-----BEGIN ')) return caSetting;
return fs.readFileSync(caSetting, 'utf8');
};
// Build a `fetch` implementation that trusts the given PEM-encoded CA
// bundle, suitable for assigning to `config[oidc.customFetch]`. Each call
// creates a single shared undici dispatcher so HTTP connections to the IdP
// can be reused across discovery, token-exchange, and userinfo calls.
const buildCustomFetch = (caBundle) => {
const dispatcher = new undici.Agent({connect: {ca: caBundle}});
return (url, options) => undici.fetch(url, {...options, dispatcher});
};
// Pick the token endpoint auth method to use, given the IdP's advertised
// `token_endpoint_auth_methods_supported` and any explicit override from
// settings. Pure; exported for unit testing.
//
// Preference order when no override is set:
// 1. `client_secret_post` if the IdP advertises it (matches openid-client@6's
// own default and works with every public IdP we've tested — notably
// GitLab.com, which rejects `client_secret_basic` at the token endpoint
// even though it lists it in discovery).
// 2. `client_secret_basic` if the IdP advertises only that.
// 3. `client_secret_basic` if the IdP advertises nothing we recognise (RFC
// 8414 §2 says the absence of the field defaults to `client_secret_basic`).
const pickAuthMethod = (supported, override) => {
if (override) return override;
if (Array.isArray(supported)) {
if (supported.includes('client_secret_post')) return 'client_secret_post';
if (supported.includes('client_secret_basic')) return 'client_secret_basic';
}
return 'client_secret_basic';
};
const clientAuthFor = (method, secret) => {
switch (method) {
case 'client_secret_basic':
// eslint-disable-next-line new-cap
return oidc.ClientSecretBasic(secret);
case 'client_secret_post':
// eslint-disable-next-line new-cap
return oidc.ClientSecretPost(secret);
default:
throw new Error(`Unsupported token endpoint auth method: ${method}`);
}
};
const fetchServerMetadata = async (issuerUrl, clientId, customFetch) => {
const url = new URL(issuerUrl);
// https://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery says that the URI
// must not have query or fragment components.
if (url.search) {
throw new Error(`Unexpected query in issuer URL (${url}): ${url.search}`);
}
if (url.hash) {
throw new Error(`Unexpected fragment in issuer URL (${url}): ${url.hash}`);
}
// openid-client@6 rejects http:// issuers by default; opt back in for
// localhost / private-network providers (matches v5 behaviour).
const options = {};
if (url.protocol === 'http:') options.execute = [oidc.allowInsecureRequests];
// `customFetch` must be set on the options bag (not on `execute`) so that
// discovery's OWN HTTPS request to /.well-known/openid-configuration uses
// it. `execute` callbacks only run AFTER discovery finishes.
if (customFetch != null) options[oidc.customFetch] = customFetch;
try {
// Discovery fetches the .well-known/openid-configuration document. The
// clientAuthentication argument is irrelevant for that HTTP request — it
// only matters when the Configuration is later used to exchange a code
// for a token — so we can pass `undefined` here and bind the real method
// below once we know what the IdP supports.
const tempConfig = await oidc.discovery(
url, clientId, undefined, undefined,
Object.keys(options).length || Object.getOwnPropertySymbols(options).length
? options : undefined);
return tempConfig.serverMetadata();
} catch (err) {
// The URL used to get the issuer metadata doesn't exactly follow RFC 8615; see:
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
const discoveryUrl = new URL(url);
if (!discoveryUrl.pathname.includes('/.well-known/')) {
discoveryUrl.pathname =
`${discoveryUrl.pathname.replace(/\/$/, '')}/.well-known/openid-configuration`;
}
logger.error(
'Failed to discover issuer metadata via OpenID Connect Discovery ' +
'(https://openid.net/specs/openid-connect-discovery-1_0.html). ' +
`Does your issuer support Discovery? (hint: ${discoveryUrl})`);
throw err;
}
};
const buildConfig = async (settings) => {
// If the operator gave us a custom CA bundle, build a fetch that trusts
// it; otherwise leave the default fetch in place. We deliberately build
// the customFetch BEFORE discovery so the discovery HTTP call itself
// uses the trusted CA — the configured IdP is typically the same host
// that serves the well-known document.
const caBundle = loadCaBundle(settings.ca);
const customFetch = caBundle ? buildCustomFetch(caBundle) : null;
// Resolve the server metadata (either via discovery or from the inline
// `issuer_metadata` blob) BEFORE choosing an auth method, so we can pick
// one the IdP actually advertises.
let serverMetadata;
let phaseLog;
if (settings.issuer) {
serverMetadata =
await fetchServerMetadata(settings.issuer, settings.client_id, customFetch);
phaseLog = 'OpenID Connect Discovery complete.';
} else {
serverMetadata = settings.issuer_metadata;
phaseLog = 'Configured from issuer_metadata.';
}
const method = pickAuthMethod(
serverMetadata && serverMetadata.token_endpoint_auth_methods_supported,
settings.token_endpoint_auth_method);
const clientAuth = clientAuthFor(method, settings.client_secret);
const config = new oidc.Configuration(
serverMetadata, settings.client_id, undefined, clientAuth);
if (isHttp(serverMetadata && serverMetadata.issuer)) {
oidc.allowInsecureRequests(config);
}
if (customFetch != null) config[oidc.customFetch] = customFetch;
const source = settings.token_endpoint_auth_method ? 'configured' : 'auto-picked';
logger.info(`${phaseLog} Token endpoint auth method: ${method} (${source})` +
(caBundle ? ' with custom CA bundle.' : '.'));
return config;
};
exports.init_ep_openid_connect = async (hookName, {logger: l}) => {
if (l != null) logger = l;
await loadOidc();
};
exports.loadSettings = async (hookName, {settings: {ep_openid_connect: s = {}}}) => {
oidcConfig = null;
settings = null;
await loadOidc();
if (!validSettings(s)) {
logger.error('Invalid settings. Detailed validation errors:', validSettings.errors);
return;
}
if ((s.issuer == null) === (s.issuer_metadata == null)) {
logger.error('Either ep_openid_connect.issuer or .issuer_metadata must be set (but not both)');
return;
}
if ('username' in (s.user_properties || {})) {
logger.error('ep_openid_connect.user_properties.username must not be set');
return;
}
settings = {
...defaultSettings,
...s,
user_properties: {
displayname: {claim: 'name'},
...s.user_properties,
// The username property must always match the key used in settings.users.
username: {claim: 'sub'},
},
};
// Make sure base_url ends with '/' so that relative URLs are appended:
if (!settings.base_url.endsWith('/')) settings.base_url += '/';
logger.debug('Settings:', {...settings, client_secret: '********'});
oidcConfig = await buildConfig(settings);
};
exports.expressCreateServer = (hookName, {app}) => {
logger.debug('Configuring auth routes');
app.get(ep('callback'), async (req, res, next) => {
// This handler MUST NOT redirect to a page that requires authentication if there is a problem,
// otherwise the user could be caught in an infinite redirect loop.
try {
logger.debug(`Processing ${req.url}`);
if (oidcConfig == null) {
logger.warn('Not configured; ignoring request.');
return next();
}
const oidcSession = req.session.ep_openid_connect || {};
if (oidcSession.callbackChecks == null) throw new Error('missing authentication checks');
const tokens = await oidc.authorizationCodeGrant(oidcConfig, callbackUrlFromRequest(req), {
expectedNonce: oidcSession.callbackChecks.nonce,
expectedState: oidcSession.callbackChecks.state,
pkceCodeVerifier: oidcSession.callbackChecks.code_verifier,
idTokenExpected: true,
});
const claims = tokens.claims();
const userinfo =
await oidc.fetchUserInfo(oidcConfig, tokens.access_token, claims && claims.sub);
validateSubClaim(userinfo.sub);
// The user has successfully authenticated, but don't set req.session.user here -- do it in
// the authenticate hook so that Etherpad can log the authentication success. However, DO "log
// out" the previous user to force the authenticate hook to run in case the user was already
// authenticated as someone else.
delete req.session.user;
// userinfo should not be stored in req.session until after all checks have passed. (Otherwise
// it would be too easy to accidentally introduce a vulnerability.)
oidcSession.userinfo = userinfo;
res.redirect(303, oidcSession.next || settings.base_url);
// Defer deletion of state until success so that the user can reload the page to retry after a
// transient backchannel failure.
delete oidcSession.callbackChecks;
delete oidcSession.next;
} catch (err) {
return next(err);
}
});
app.get(ep('login'), async (req, res, next) => {
try {
logger.debug(`Processing ${req.url}`);
if (oidcConfig == null) {
logger.warn('Not configured; ignoring request.');
return next();
}
if (req.session.ep_openid_connect == null) req.session.ep_openid_connect = {};
const oidcSession = req.session.ep_openid_connect;
const code_verifier = oidc.randomPKCECodeVerifier(); // RFC7636
const code_challenge = await oidc.calculatePKCECodeChallenge(code_verifier);
const nonce = oidc.randomNonce();
const state = oidc.randomState();
oidcSession.callbackChecks = {nonce, state, code_verifier};
const url = oidc.buildAuthorizationUrl(oidcConfig, {
redirect_uri: endpointUrl('callback'),
scope: settings.scope.join(' '),
nonce,
state,
code_challenge,
code_challenge_method: 'S256',
});
res.redirect(303, url.toString());
} catch (err) {
return next(err);
}
});
app.get(ep('logout'), (req, res, next) => {
logger.debug(`Processing ${req.url}`);
if (oidcConfig == null) {
logger.warn('Not configured; ignoring request.');
return next();
}
req.session.destroy(() => res.redirect(303, settings.base_url));
});
};
exports.authenticate = (hookName, {req, res, users}) => {
if (oidcConfig == null) return;
logger.debug('authenticate hook for', req.url);
const {ep_openid_connect: {userinfo} = {}} = req.session;
if (userinfo == null) { // Nullish means the user isn't authenticated.
// Out of an abundance of caution, clear out the old state, nonce, and userinfo (if present) to
// force regeneration.
delete req.session.ep_openid_connect;
// Authn failed. Let another plugin try to authenticate the user.
return;
}
// Successfully authenticated.
logger.info('Successfully authenticated user with userinfo:', userinfo);
req.session.user = users[userinfo.sub];
if (req.session.user == null) req.session.user = users[userinfo.sub] = {};
for (const [propName, descriptor] of Object.entries(settings.user_properties)) {
if (descriptor == null) {
delete req.session.user[propName];
} else if (descriptor.claim != null && descriptor.claim in userinfo) {
req.session.user[propName] = userinfo[descriptor.claim];
} else if (descriptor.role != null && Array.isArray(userinfo.roles) &&
userinfo.roles.includes(descriptor.role)) {
// Boolean `true` (not the string `"true"`) so that the value works
// directly with Etherpad's is_admin/readOnly/canCreate checks.
req.session.user[propName] = true;
} else if ('default' in descriptor && !(propName in req.session.user)) {
req.session.user[propName] = descriptor.default;
}
}
logger.debug('User properties:', req.session.user);
return true;
};
exports.authnFailure = (hookName, {req, res}) => {
if (oidcConfig == null) return;
// Normally the user is redirected to the login page which would then redirect the user back once
// authenticated. For non-GET requests, send a 401 instead because users can't be redirected back.
// Also send a 401 if an Authorization header is present to facilitate API error handling.
//
// 401 is the status that most closely matches the desired semantics. However, RFC7235 section
// 3.1 says, "The server generating a 401 response MUST send a WWW-Authenticate header field
// containing at least one challenge applicable to the target resource." Etherpad uses a token
// (signed session identifier) transmitted via cookie for authentication, but there is no
// standard authentication scheme name for that. So we use a non-standard name here.
//
// We could theoretically implement Bearer authorization (RFC6750), but it's unclear to me how
// to do this correctly and securely:
// * The userinfo endpoint is meant for the OAuth client, not the resource server, so it
// shouldn't be used to look up claims.
// * In general, access tokens might be opaque (not JWTs) so we can't get claims by parsing
// them.
// * The token introspection endpoint should return scope and subject (I think?), but probably
// not claims.
// * If claims can't be used to convey access level, how is it conveyed? Scope? Resource
// indicators (RFC8707)?
// * How is intended audience checked? Or is introspection guaranteed to do that for us?
// * Should tokens be limited to a particular pad?
// * Bearer tokens are only meant to convey authorization; authentication is handled by the
// authorization server. Should Bearer tokens be processed during the authorize hook?
// * How should bearer authentication interact with authorization plugins?
// * How should bearer authentication interact with plugins that add new endpoints?
// * Would we have to implement our own OAuth server to issue access tokens?
res.header('WWW-Authenticate', 'Etherpad');
if (!['GET', 'HEAD'].includes(req.method) || req.headers.authorization) {
res.status(401).end();
return true;
}
if (req.session.ep_openid_connect == null) req.session.ep_openid_connect = {};
req.session.ep_openid_connect.next = new URL(req.url.slice(1), settings.base_url).toString();
res.redirect(303, endpointUrl('login'));
return true;
};
exports.preAuthorize = (hookName, {req}) => {
if (oidcConfig == null) return;
if (req.path.startsWith(ep(''))) return true;
return;
};
exports.exportedForTestingOnly = {
callbackUrlFromRequest,
defaultSettings,
loadCaBundle,
pickAuthMethod,
validSettings,
};