-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenid_connect.js
executable file
·444 lines (402 loc) · 18.4 KB
/
openid_connect.js
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
/*
* JavaScript functions for providing OpenID Connect with NGINX Plus
*
* Copyright (C) 2020 Nginx, Inc.
*/
var newSession = false; // Used by oidcAuth() and validateIdToken()
export default {auth, codeExchange, validateIdToken, logout, redirectPostLogout};
function retryOriginalRequest(r) {
delete r.headersOut["WWW-Authenticate"]; // Remove evidence of original failed auth_jwt
r.internalRedirect(r.variables.uri + r.variables.is_args + (r.variables.args || ''));
}
// If the ID token has not been synced yet, poll the variable every 100ms until
// get a value or after a timeout.
function waitForSessionSync(r, timeLeft) {
if (r.variables.session_jwt) {
retryOriginalRequest(r);
} else if (timeLeft > 0) {
setTimeout(waitForSessionSync, 100, r, timeLeft - 100);
} else {
auth(r, true);
}
}
function auth(r, afterSyncCheck) {
if (isClientCredentialFlow(r)) {
clientCredentialFlow(r);
return;
}
authCodeFlow(r, afterSyncCheck);
}
function authCodeFlow(r, afterSyncCheck) {
// If a cookie was sent but the ID token is not in the key-value database, wait for the token to be in sync.
if (r.variables.cookie_auth_token && !r.variables.session_jwt && !afterSyncCheck && r.variables.zone_sync_leeway > 0) {
waitForSessionSync(r, r.variables.zone_sync_leeway);
return;
}
if (!r.variables.refresh_token || r.variables.refresh_token == "-") {
newSession = true;
// Check we have all necessary configuration variables (referenced only by njs)
var oidcConfigurables = ["authz_endpoint", "scopes", "hmac_key", "cookie_flags"];
var missingConfig = [];
for (var i in oidcConfigurables) {
if (!r.variables["oidc_" + oidcConfigurables[i]] || r.variables["oidc_" + oidcConfigurables[i]] == "") {
missingConfig.push(oidcConfigurables[i]);
}
}
if (missingConfig.length) {
r.error("OIDC missing configuration variables: $oidc_" + missingConfig.join(" $oidc_"));
r.return(500, r.variables.internal_error_message);
return;
}
// Redirect the client to the IdP login page with the cookies we need for state
r.return(302, r.variables.oidc_authz_endpoint + getAuthZArgs(r));
return;
}
// Pass the refresh token to the /_refresh location so that it can be
// proxied to the IdP in exchange for a new id_token
r.subrequest("/_refresh", "token=" + r.variables.refresh_token,
function(reply) {
if (reply.status != 200) {
// Refresh request failed, log the reason
var error_log = "OIDC refresh failure";
if (reply.status == 504) {
error_log += ", timeout waiting for IdP";
} else if (reply.status == 400) {
try {
var errorset = JSON.parse(reply.responseBody);
error_log += ": " + errorset.error + " " + errorset.error_description;
} catch (e) {
error_log += ": " + reply.responseBody;
}
} else {
error_log += " " + reply.status;
}
r.error(error_log);
// Clear the refresh token, try again
r.variables.refresh_token = "-";
r.return(302, r.variables.request_uri);
return;
}
// Refresh request returned 200, check response
try {
var tokenset = JSON.parse(reply.responseBody);
if (!tokenset.id_token) {
r.error("OIDC refresh response did not include id_token");
if (tokenset.error) {
r.error("OIDC " + tokenset.error + " " + tokenset.error_description);
}
r.variables.refresh_token = "-";
r.return(302, r.variables.request_uri);
return;
}
// Send the new ID Token to auth_jwt location for validation
r.subrequest("/_id_token_validation", "token=" + tokenset.id_token,
function(reply) {
if (reply.status != 204) {
r.variables.refresh_token = "-";
r.return(302, r.variables.request_uri);
return;
}
// ID Token is valid, update keyval
r.log("OIDC refresh success, updating id_token for " + r.variables.cookie_auth_token);
r.variables.session_jwt = tokenset.id_token; // Update key-value store
if (tokenset.access_token) {
r.variables.access_token = tokenset.access_token;
} else {
r.variables.access_token = "";
}
// Update refresh token (if we got a new one)
if (r.variables.refresh_token != tokenset.refresh_token) {
r.log("OIDC replacing previous refresh token (" + r.variables.refresh_token + ") with new value: " + tokenset.refresh_token);
r.variables.refresh_token = tokenset.refresh_token; // Update key-value store
}
retryOriginalRequest(r); // Continue processing original request
}
);
} catch (e) {
r.variables.refresh_token = "-";
r.return(302, r.variables.request_uri);
return;
}
}
);
}
function codeExchange(r) {
// First check that we received an authorization code from the IdP
if (r.variables.arg_code == undefined || r.variables.arg_code.length == 0) {
if (r.variables.arg_error) {
r.error("OIDC error receiving authorization code from IdP: " + r.variables.arg_error_description);
} else {
r.error("OIDC expected authorization code from IdP but received: " + r.uri);
}
r.return(502);
return;
}
// Pass the authorization code to the /_token location so that it can be
// proxied to the IdP in exchange for a JWT
r.subrequest("/_token",idpClientAuth(r), function(reply) {
if (reply.status == 504) {
r.error("OIDC timeout connecting to IdP when sending authorization code");
r.return(504);
return;
}
if (reply.status != 200) {
try {
var errorset = JSON.parse(reply.responseBody);
if (errorset.error) {
r.error("OIDC error from IdP when sending authorization code: " + errorset.error + ", " + errorset.error_description);
} else {
r.error("OIDC unexpected response from IdP when sending authorization code (HTTP " + reply.status + "). " + reply.responseBody);
}
} catch (e) {
r.error("OIDC unexpected response from IdP when sending authorization code (HTTP " + reply.status + "). " + reply.responseBody);
}
r.return(502);
return;
}
// Code exchange returned 200, check for errors
try {
var tokenset = JSON.parse(reply.responseBody);
if (tokenset.error) {
r.error("OIDC " + tokenset.error + " " + tokenset.error_description);
r.return(500);
return;
}
// Send the ID Token to auth_jwt location for validation
r.subrequest("/_id_token_validation", "token=" + tokenset.id_token,
function(reply) {
if (reply.status != 204) {
r.return(500); // validateIdToken() will log errors
return;
}
// If the response includes a refresh token then store it
if (tokenset.refresh_token) {
r.variables.new_refresh = tokenset.refresh_token; // Create key-value store entry
r.log("OIDC refresh token stored");
} else {
r.warn("OIDC no refresh token");
}
// Add opaque token to keyval session store
r.log("OIDC success, creating session " + r.variables.request_id);
r.variables.new_session = tokenset.id_token; // Create key-value store entry
if (tokenset.access_token) {
r.variables.new_access_token = tokenset.access_token;
} else {
r.variables.new_access_token = "";
}
r.headersOut["Set-Cookie"] = "auth_token=" + r.variables.request_id + "; " + r.variables.oidc_cookie_flags;
redirectPostLogin(r);
}
);
} catch (e) {
r.error("OIDC authorization code sent but token response is not JSON. " + reply.responseBody);
r.return(502);
}
}
);
}
function validateIdToken(r) {
// Check mandatory claims
var required_claims = ["iat", "iss", "sub"]; // aud is checked separately
var missing_claims = [];
for (var i in required_claims) {
if (r.variables["jwt_claim_" + required_claims[i]].length == 0 ) {
missing_claims.push(required_claims[i]);
}
}
if (r.variables.jwt_audience.length == 0) missing_claims.push("aud");
if (missing_claims.length) {
r.error("OIDC ID Token validation error: missing claim(s) " + missing_claims.join(" "));
r.return(403);
return;
}
var validToken = true;
// Check iat is a positive integer
var iat = Math.floor(Number(r.variables.jwt_claim_iat));
if (String(iat) != r.variables.jwt_claim_iat || iat < 1) {
r.error("OIDC ID Token validation error: iat claim is not a valid number");
validToken = false;
}
// Audience matching
var aud = r.variables.jwt_audience.split(",");
if (!aud.includes(r.variables.oidc_client)) {
r.error("OIDC ID Token validation error: aud claim (" + r.variables.jwt_audience + ") does not include configured $oidc_client (" + r.variables.oidc_client + ")");
validToken = false;
}
// If we receive a nonce in the ID Token then we will use the auth_nonce cookies
// to check that the JWT can be validated as being directly related to the
// original request by this client. This mitigates against token replay attacks.
if (newSession) {
var client_nonce_hash = "";
if (r.variables.cookie_auth_nonce) {
var c = require('crypto');
var h = c.createHmac('sha256', r.variables.oidc_hmac_key).update(r.variables.cookie_auth_nonce);
client_nonce_hash = h.digest('base64url');
}
if (r.variables.jwt_claim_nonce != client_nonce_hash) {
r.error("OIDC ID Token validation error: nonce from token (" + r.variables.jwt_claim_nonce + ") does not match client (" + client_nonce_hash + ")");
validToken = false;
}
}
if (validToken) {
r.return(204);
} else {
r.return(403);
}
}
// Default RP-Initiated or Custom Logout w/ OP as per:
// https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RPLogout
// https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RedirectionAfterLogout
// An RP requests that the OP log out the end-user by redirecting the end-user's
// User Agent to the OP's Logout endpoint.
function logout(r) {
r.log("OIDC logout for " + r.variables.cookie_auth_token);
var queryParams = '';
if (r.variables.oidc_end_session_query_params) {
queryParams = '?' + r.variables.oidc_end_session_query_params;
}
r.variables.session_jwt = "-";
r.variables.access_token = "-";
r.variables.refresh_token = "-";
r.return(302, r.variables.oidc_end_session_endpoint + queryParams);
}
function getAuthZArgs(r) {
// Choose a nonce for this flow for the client, and hash it for the IdP
var noncePlain = r.variables.request_id;
var c = require('crypto');
var h = c.createHmac('sha256', r.variables.oidc_hmac_key).update(noncePlain);
var nonceHash = h.digest('base64url');
var authZArgs = "?response_type=code&scope=" + r.variables.oidc_scopes + "&client_id=" + r.variables.oidc_client + "&redirect_uri="+ r.variables.redirect_base + r.variables.redir_location + "&nonce=" + nonceHash;
if (r.variables.oidc_authz_extra_args) {
authZArgs += "&" + r.variables.oidc_authz_extra_args;
}
r.headersOut['Set-Cookie'] = [
"auth_redir=" + r.variables.request_uri + "; " + r.variables.oidc_cookie_flags,
"auth_nonce=" + noncePlain + "; " + r.variables.oidc_cookie_flags
];
if ( r.variables.oidc_pkce_enable == 1 ) {
var pkce_code_verifier = c.createHmac('sha256', r.variables.oidc_hmac_key).update(String(Math.random())).digest('hex');
r.variables.pkce_id = c.createHash('sha256').update(String(Math.random())).digest('base64url');
var pkce_code_challenge = c.createHash('sha256').update(pkce_code_verifier).digest('base64url');
r.variables.pkce_code_verifier = pkce_code_verifier;
authZArgs += "&code_challenge_method=S256&code_challenge=" + pkce_code_challenge + "&state=" + r.variables.pkce_id;
} else {
authZArgs += "&state=0";
}
return authZArgs;
}
function idpClientAuth(r) {
// If PKCE is enabled we have to use the code_verifier
if ( r.variables.oidc_pkce_enable == 1 ) {
r.variables.pkce_id = r.variables.arg_state;
return "code=" + r.variables.arg_code + "&code_verifier=" + r.variables.pkce_code_verifier;
} else {
return "code=" + r.variables.arg_code + "&client_secret=" + r.variables.oidc_client_secret;
}
}
// Redirect URI after successful login from the OP.
function redirectPostLogin(r) {
if (r.variables.oidc_landing_page) {
r.return(302, r.variables.oidc_landing_page);
} else {
r.return(302, r.variables.redirect_base + r.variables.cookie_auth_redir);
}
}
// Redirect URI after logged-out from the OP.
function redirectPostLogout(r) {
r.return(302, r.variables.oidc_logout_landing_page);
}
// Check if grant type is Client Credentials Flow.
function isClientCredentialFlow(r) {
if (!r.variables.oidc_client_credentials_flow_enable) {
return false;
}
return ('Authorization' in r.headersIn);
// TODO: Remove this if the specific variable isn't used in the header
// for Client Credential Flow
// try {
// let grantType = r.headersIn['Nginx-Management-Suite-GrantType'];
// if (grantType === 'ClientCredentialsFlow') {
// return true
// } else {
// return false;
// }
// // TODO: Validate access token if needed.
// } catch (e) {
// return false;
// }
}
// Extract Bearer token and get client ID/secret parameters
function getClientIDSecretParamsFromBearerToken(r) {
// TODO: add a logic to extract Bearer token and set client ID and secret.
let clientID = r.variables.oidc_client;
let clientSecret = r.variables.oidc_client_secret;
let params = '&client_id=' + clientID + "&client_secret=" + clientSecret;
return params
}
// Start Client Credentials Flow
function clientCredentialFlow(r) {
if (r.variables.access_token) {
// TODO: do not return if access_token is expired
return;
}
// TODO: Extract bearer token and set client ID and secret in the params.
let defaultParams = getClientIDSecretParamsFromBearerToken(r);
// TODO: check if access token has been synched between zones.
r.log("start Client Credentials Flow");
let req_body = "grant_type=client_credentials" + defaultParams +
"&" + r.variables.oidc_client_credentials_token_body;
let req = {
method: "POST",
body: req_body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
r.subrequest("/_token_client_credentials", req, function(reply) {
if (reply.status == 504) {
r.error("OIDC timeout connecting to IdP when starting Client Credential Flow");
r.return(504);
return;
}
if (reply.status != 200) {
try {
var errorset = JSON.parse(reply.responseBody);
if (errorset.error) {
r.error("OIDC error from IdP when starting Client Credential Flow: " + errorset.error + ", " + errorset.error_description);
} else {
r.error("OIDC unexpected response from IdP starting Client Credential Flow (HTTP " + reply.status + "). " + reply.responseBody);
}
} catch (e) {
r.error("OIDC unexpected response from IdP starting Client Credential Flow (HTTP " + reply.status + "). " + reply.responseBody);
}
r.return(502);
return;
}
// Token endpoint returned 200, and check for errors.
try {
var tokenset = JSON.parse(reply.responseBody);
if (tokenset.error) {
r.error("OIDC " + tokenset.error + " " + tokenset.error_description);
r.return(500);
return;
}
// TODO: access token validation if necessary
// Update access token in key/value store
if (tokenset.access_token) {
r.variables.new_access_token = tokenset.access_token;
} else {
r.variables.new_access_token = "";
}
let redirectURI = r.variables.request_uri + "; " + r.variables.oidc_cookie_flags;
r.headersOut['Set-Cookie'] = [
"auth_token=" + r.variables.request_id + "; " + r.variables.oidc_cookie_flags,
"auth_redir=" + redirectURI,
];
r.return(302, r.variables.redirect_base + redirectURI);
} catch (e) {
r.error("OIDC Client Credential Flow requested but token response is not JSON. " + reply.responseBody);
r.return(502);
}
});
}