-
Notifications
You must be signed in to change notification settings - Fork 44
/
index.js
1481 lines (1279 loc) · 42.6 KB
/
index.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
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { Assertion } = require("../../assertion");
const { BasePlugin } = require("../../plugin");
const { Issuer } = require("openid-client");
const jwt = require("jsonwebtoken");
const oauth2 = require("simple-oauth2");
const queryString = require("query-string");
const request = require("request");
const URI = require("uri-js");
Issuer.useRequest();
Issuer.defaultHttpOptions = { timeout: 10000, headers: {} };
const exit_failure = function(message = "", code = 1) {
if (message) {
console.log(message);
}
process.exit(code);
};
const issuer_encrypt_secret =
process.env.EAS_ISSUER_ENCRYPT_SECRET ||
exit_failure("missing EAS_ISSUER_ENCRYPT_SECRET env variable");
const issuer_sign_secret =
process.env.EAS_ISSUER_SIGN_SECRET ||
exit_failure("missing EAS_ISSUER_SIGN_SECRET env variable");
const SESSION_CACHE_PREFIX = "session:oauth:";
const DEFAULT_COOKIE_NAME = "_eas_oauth_session";
const HANDLER_INDICATOR_PARAM_NAME = "__eas_oauth_handler__";
const STATE_CSRF_COOKIE_NAME = "_eas_oauth_csrf";
const STATE_CSRF_COOKIE_EXPIRY = "43200"; //12 hours
const DEFAULT_CLIENT_CLOCK_TOLERANCE = 5;
const ISSUER_CACHE_DURATION = 43200 * 1000;
const CLIENT_CACHE_DURATION = 43200 * 1000;
let initialized = false;
function token_is_expired(token) {
return !!(token.exp && token.exp < Date.now() / 1000);
}
function token_is_premature(token) {
return !!(token.nbf && token.nbf < Date.now() / 1000);
}
function token_issuer_match(token, issuer) {
return token.iss && token.iss == issuer;
}
function tokenset_is_expired(tokenSet) {
if (tokenSet.expires_at) {
return !!(tokenSet.expires_at < Date.now() / 1000);
}
if (tokenSet.id_token) {
return token_is_expired(jwt.decode(tokenSet.id_token));
}
return false;
}
function tokenset_is_premature(tokenSet) {
if (tokenSet.id_token) {
return token_is_premature(jwt.decode(tokenSet.id_token));
}
return false;
}
function tokenset_issuer_match(tokenSet, issuer) {
if (tokenSet.id_token) {
return token_issuer_match(jwt.decode(tokenSet.id_token), issuer);
}
return true;
}
function tokenset_can_refresh(tokenSet) {
if (!tokenSet.refresh_token) {
return false;
}
let refreshToken;
try {
refreshToken = jwt.decode(tokenSet.refresh_token);
return !!!token_is_expired(refreshToken);
} catch (e) {
return true;
}
}
function tokenset_refresh_can_expire(tokenSet) {
if (!tokenSet.refresh_token) {
return false;
}
if (tokenSet.refresh_expires_in) {
return true;
}
try {
refreshToken = jwt.decode(tokenSet.refresh_token);
if (refreshToken.exp) {
return true;
}
} catch (e) {}
return false;
}
function tokenset_refresh_expire_at(tokenSet) {
if (tokenset_refresh_can_expire(tokenSet)) {
//TODO: implement this somehow
}
return null;
}
class BaseOauthPlugin extends BasePlugin {
static initialize(server) {
if (!initialized) {
server.WebServer.get("/oauth/callback", (req, res) => {
server.logger.silly("%j", {
headers: req.headers,
body: req.body
});
try {
let state = server.utils.decrypt(
issuer_encrypt_secret,
req.query.state,
"hex"
);
state = jwt.verify(state, issuer_sign_secret);
const state_redirect_uri = state.request_uri;
const parsedStateRedirectURI = URI.parse(state_redirect_uri);
server.logger.verbose(
"parsed state redirect uri: %j",
parsedStateRedirectURI
);
const parsedRequestURI = URI.parse(req.url);
server.logger.verbose("parsed request uri: %j", parsedRequestURI);
const parsedRedirectURI = Object.assign({}, parsedStateRedirectURI);
parsedRedirectURI.query = parsedRequestURI.query;
server.logger.verbose("parsed redirect uri: %j", parsedRedirectURI);
const redirect_uri = URI.serialize(parsedRedirectURI);
server.logger.info("redirecting browser to: %j", redirect_uri);
res.statusCode = 302;
res.setHeader("Location", redirect_uri);
res.end();
return;
} catch (e) {
server.logger.error(e);
res.statusCode = 503;
res.end();
}
});
initialized = true;
}
}
/**
* Verify the request
*
* @name verify
* @param {*} configToken
* @param {*} req
*/
async verify(configToken, req, res) {
const plugin = this;
const store = plugin.server.store;
const client = await plugin.get_client();
const pluginStrategy =
plugin.constructor.name == "OpenIdConnectPlugin" ? "oidc" : "oauth2";
const PLUGIN_STRATEGY_OAUTH = "oauth";
const PLUGIN_STRATEGY_OIDC = "oidc";
/**
* reconstruct original request info from headers etc
*/
const parentReqInfo = plugin.server.utils.get_parent_request_info(req);
plugin.server.logger.verbose("parent request info: %j", parentReqInfo);
const configAudMD5 = configToken.audMD5;
plugin.server.logger.verbose("audMD5: %s", configAudMD5);
const configCookieName = this.config.cookie.name;
plugin.server.logger.verbose("cooking name: %s", configCookieName);
const redirectHttpCode = req.query.redirect_http_code
? req.query.redirect_http_code
: 302;
const authorization_redirect_uri = plugin.get_authorization_redirect_uri(
parentReqInfo.uri
);
const respond_to_failed_authorization = async function() {
plugin.server.logger.verbose(
"redirect_uri: %s",
authorization_redirect_uri
);
const payload = {
request_uri: parentReqInfo.uri,
aud: configAudMD5,
csrf: plugin.server.utils.generate_csrf_id()
};
const stateToken = jwt.sign(payload, issuer_sign_secret);
const state = plugin.server.utils.encrypt(
issuer_encrypt_secret,
stateToken,
"hex"
);
const url = await plugin.get_authorization_url(
authorization_redirect_uri,
state
);
plugin.server.logger.verbose("callback redirect_uri: %s", url);
switch (redirectHttpCode) {
case 401:
res.setHeader(
"WWW-Authenticate",
'Bearer realm="' +
authorization_redirect_uri +
', scope="' +
plugin.config.scopes.join(" ") +
'"'
);
default:
res.cookie(
STATE_CSRF_COOKIE_NAME,
plugin.server.utils.encrypt(
plugin.server.secrets.cookie_encrypt_secret,
payload.csrf
),
{
expires: new Date(Date.now() + STATE_CSRF_COOKIE_EXPIRY * 1000),
httpOnly: true, //kills js access
signed: true
}
);
res.statusCode = redirectHttpCode;
res.setHeader("Location", url);
return res;
}
};
/**
* state should be the decrypted and decoded state token
*
*
* @param {*} req
* @param {*} res
* @param {*} state
*/
const handle_auth_callback_request = async function(
configToken,
req,
res,
state,
parentReqInfo
) {
const redirectHttpCode = req.query.redirect_http_code
? req.query.redirect_http_code
: 302;
plugin.server.logger.verbose("decoded state: %j", state);
const configAudMD5 = configToken.audMD5;
plugin.server.logger.verbose("audMD5: %s", configAudMD5);
const configCookieName = plugin.config.cookie.name;
plugin.server.logger.verbose("cooking name: %s", configCookieName);
/**
* check for csrf cookie presense
*/
if (!req.signedCookies[STATE_CSRF_COOKIE_NAME]) {
res.statusCode = 503;
return res;
}
/**
* validate csrf token
*/
if (
state.csrf !=
plugin.server.utils.decrypt(
plugin.server.secrets.cookie_encrypt_secret,
req.signedCookies[STATE_CSRF_COOKIE_NAME]
)
) {
res.statusCode = 503;
return res;
}
plugin.server.logger.verbose("begin token fetch with authorization code");
const compare_redirect_uri = plugin.get_authorization_redirect_uri(
state.request_uri
);
plugin.server.logger.verbose(
"compare_redirect_uri: %s",
compare_redirect_uri
);
let tokenSet;
try {
tokenSet = await plugin.authorization_code_callback(
parentReqInfo,
compare_redirect_uri
);
} catch (e) {
plugin.server.logger.error(e);
if (plugin.is_redirectable_error(e)) {
res.statusCode = redirectHttpCode;
res.setHeader("Location", state.request_uri);
return res;
}
res.statusCode = 503;
return res;
}
plugin.server.logger.verbose("received and validated tokens");
plugin.log_token_set(tokenSet);
const tokenSetValid = await plugin.token_set_asertions(tokenSet);
if (!tokenSetValid) {
res.statusCode = 403;
return res;
}
/**
* only id_token is guaranteed to be a jwt
*/
let idToken;
if (tokenSet.id_token) {
idToken = jwt.decode(tokenSet.id_token);
}
//TODO: see if expires_at is access_token or refresh_token, adjust logic accordingly
let cookieExpiresAt, sessionExpiresAt, tokenExpiresAt;
if (tokenSet.expires_at) {
tokenExpiresAt = tokenSet.expires_at * 1000;
} else if (idToken) {
if (idToken.exp) {
tokenExpiresAt = idToken.exp * 1000;
}
}
if (plugin.config.features.cookie_expiry === false) {
cookieExpiresAt = null;
} else if (
plugin.config.features.cookie_expiry !== true &&
plugin.config.features.cookie_expiry > 0
) {
cookieExpiresAt =
Date.now() / 1000 + plugin.config.features.session_expiry;
cookieExpiresAt = cookieExpiresAt * 1000;
} else {
cookieExpiresAt = tokenExpiresAt;
}
if (plugin.config.features.session_expiry === false) {
sessionExpiresAt = null;
} else if (
plugin.config.features.session_expiry !== true &&
plugin.config.features.session_expiry > 0
) {
sessionExpiresAt =
Date.now() / 1000 + plugin.config.features.session_expiry;
sessionExpiresAt = sessionExpiresAt * 1000;
} else {
sessionExpiresAt = tokenExpiresAt;
}
let sessionPayload = {
iat: Math.floor(Date.now() / 1000),
tokenSet,
aud: configAudMD5
};
let userinfo;
if (plugin.config.features.fetch_userinfo) {
userinfo = await plugin.get_userinfo(tokenSet);
plugin.server.logger.verbose("userinfo %j", userinfo);
if (userinfo && userinfo.data) {
sessionPayload.userinfo = userinfo;
}
}
if (plugin.config.assertions.userinfo) {
const userinfoValid = await plugin.userinfo_assertions(
sessionPayload.userinfo.data
);
if (!userinfoValid) {
res.statusCode = 403;
return res;
}
}
let session_id;
if (
plugin.config.features.session_retain_id === true &&
req.signedCookies[configCookieName]
) {
session_id = req.signedCookies[configCookieName];
plugin.server.logger.verbose("re-creating session: %s", session_id);
} else {
session_id = plugin.server.utils.generate_session_id();
plugin.server.logger.verbose("creating new session: %s", session_id);
}
let ttl = null;
if (sessionExpiresAt) {
sessionPayload.exp = Math.floor(sessionExpiresAt / 1000);
ttl = (sessionExpiresAt - Date.now()) / 1000;
}
await plugin.save_session(session_id, sessionPayload, ttl);
res.cookie(configCookieName, session_id, {
domain: plugin.config.cookie.domain,
path: plugin.config.cookie.path,
/**
* if omitted will be a 'session' cookie
*/
expires: cookieExpiresAt ? new Date(cookieExpiresAt) : null,
httpOnly: true, //kills js access
signed: true
});
/**
* remove the csrf cookie
*/
res.clearCookie(STATE_CSRF_COOKIE_NAME);
plugin.server.logger.info(
"redirecting to original resource: %s",
state.request_uri
);
res.statusCode = redirectHttpCode;
res.setHeader("Location", state.request_uri);
return res;
};
/**
* This handles callback scenarios from the provider (ie: auth succeeded or failed)
* authenticates provider
* gathers tokens
* sends token(s) as encrypted cookie(s)
* redirects to original requested URI
*
*/
switch (parentReqInfo.parsedQuery[HANDLER_INDICATOR_PARAM_NAME]) {
case "authorization_callback":
const state = plugin.server.utils.decrypt(
issuer_encrypt_secret,
parentReqInfo.parsedQuery.state,
"hex"
);
const decodedState = jwt.verify(state, issuer_sign_secret);
return handle_auth_callback_request(
configToken,
req,
res,
decodedState,
parentReqInfo
);
case "verify":
default:
/**
* This should handle 2 broad scenarios:
* 1. cookie is present and needs to be authenticated (ie: user has already been authed)
* 2. cookie is not present and user agent needs to be redirected to provider
*/
const session_id = req.signedCookies[configCookieName];
if (session_id) {
plugin.server.logger.verbose("retrieving session: %s", session_id);
let sessionPayload = await plugin.get_session_data(session_id);
if (!sessionPayload) {
plugin.server.logger.verbose("failed to retrieve session");
return respond_to_failed_authorization();
}
let tokenSet = sessionPayload.tokenSet;
plugin.log_token_set(tokenSet);
plugin.server.logger.verbose(
"comparing audience values: session=%s config=%s",
sessionPayload.aud,
configAudMD5
);
/**
* assures the session was created by the appropriate configToken
*
* TODO: should this be 503 or 401?
* TODO: clear the cookie?
*/
if (sessionPayload.aud != configAudMD5) {
plugin.server.logger.verbose("non-matching audience");
return respond_to_failed_authorization();
}
if (
sessionPayload.exp > 0 &&
Date.now() / 1000 > sessionPayload.exp
) {
plugin.server.logger.verbose("session has expired");
store.del(SESSION_CACHE_PREFIX + session_id);
return respond_to_failed_authorization();
}
/**
* refresh tokenSet
* NOTE: this process could be getting invoked by several requests resulting
* in concurrency issues where the refresh_token is no longer valid after the
* tokenSet has been refreshed by the first one through. This is alleviated
* by doing generating an md5 of the session payload before attempting to refresh.
* If the process fails fresh session data is reloaded and compared against the
* original md5. If the values have changed it's assumed another request attempted
* a refresh and succeeded.
*/
if (
tokenset_is_expired(tokenSet) &&
plugin.config.features.refresh_access_token &&
tokenset_can_refresh(tokenSet)
) {
/**
* store md5 *before* attempting refresh to test if failure due to concurrency
*/
const preSaveSessionMD5 = plugin.server.utils.md5(
JSON.stringify(sessionPayload)
);
try {
plugin.server.logger.verbose("refreshing tokenSet");
tokenSet = await plugin.refresh_token(tokenSet);
sessionPayload.tokenSet = tokenSet;
let userinfo;
if (
plugin.config.features.fetch_userinfo &&
plugin.config.features.userinfo_expiry === true
) {
plugin.server.logger.verbose("refreshing userinfo");
userinfo = await plugin.get_userinfo(tokenSet);
plugin.server.logger.verbose("userinfo %j", userinfo);
sessionPayload.userinfo = userinfo;
}
if (plugin.config.assertions.userinfo) {
const userinfoValid = await plugin.userinfo_assertions(
sessionPayload.userinfo.data
);
if (!userinfoValid) {
return respond_to_failed_authorization();
}
}
await plugin.update_session(session_id, sessionPayload);
} catch (e) {
//TODO: better logic here to detect invalid_grant, etc
const snooze = ms =>
new Promise(resolve => setTimeout(resolve, ms));
await snooze(500);
sessionPayload = await plugin.get_session_data(session_id);
tokenSet = sessionPayload.tokenSet;
const postSaveSessionMD5 = plugin.server.utils.md5(
JSON.stringify(sessionPayload)
);
/**
* if data is same before *and* after
*/
if (preSaveSessionMD5 == postSaveSessionMD5) {
plugin.server.logger.warn("tokenSet not refreshed externally");
plugin.server.logger.error(e);
if (plugin.is_redirectable_error(e)) {
return respond_to_failed_authorization();
} else {
throw e;
}
} else {
plugin.server.logger.verbose("tokenSet refreshed externally");
}
}
}
// run tokenSet assertions (including id_token assertions)
let tokenSetValid;
tokenSetValid = await plugin.token_set_asertions(tokenSet);
if (!tokenSetValid) {
plugin.server.logger.verbose("tokenSet failed assertions");
return respond_to_failed_authorization();
}
// refresh userinfo if necessary
if (
plugin.config.features.fetch_userinfo &&
plugin.config.features.userinfo_expiry !== true &&
plugin.config.features.userinfo_expiry > 0 &&
Date.now() / 1000 >
sessionPayload.userinfo.iat +
plugin.config.features.userinfo_expiry
) {
plugin.server.logger.verbose("refreshing expired userinfo");
let userinfo;
try {
userinfo = await plugin.get_userinfo(tokenSet);
plugin.server.logger.verbose("userinfo %j", userinfo);
sessionPayload.userinfo = userinfo;
await plugin.update_session(session_id, sessionPayload);
} catch (e) {
plugin.server.logger.warn("failed to retrieve userinfo");
plugin.server.logger.error(e);
if (plugin.is_redirectable_error(e)) {
return respond_to_failed_authorization();
} else {
throw e;
}
}
}
// run assertions on userinfo
if (plugin.config.assertions.userinfo) {
const userinfoValid = await plugin.userinfo_assertions(
sessionPayload.userinfo.data
);
if (!userinfoValid) {
plugin.server.logger.verbose("userinfo failed assertions");
return respond_to_failed_authorization();
}
}
let now = Date.now() / 1000;
if (
plugin.config.features.session_expiry !== true &&
plugin.config.features.session_expiry > 0 &&
sessionPayload.exp &&
plugin.config.features.session_expiry_refresh_window &&
now >=
plugin.config.features.session_expiry_refresh_window +
sessionPayload.exp
) {
await plugin.update_session(session_id, sessionPayload);
}
await plugin.prepare_token_headers(res, sessionPayload);
await plugin.prepare_authentication_data(res, sessionPayload);
res.statusCode = 200;
return res;
} else {
/**
* cookie not present, redirect to oidc provider
*/
return respond_to_failed_authorization();
}
break;
}
}
async get_session_data(session_id) {
const plugin = this;
const store = plugin.server.store;
plugin.server.logger.verbose("retrieving session: %s", session_id);
const encryptedSession = await store.get(SESSION_CACHE_PREFIX + session_id);
plugin.server.logger.verbose(
"retrieved encrypted session content: %s",
encryptedSession
);
if (!encryptedSession) {
plugin.server.logger.verbose("failed to decrypt session");
return false;
}
let sessionPayload = plugin.server.utils.decrypt(
plugin.server.secrets.session_encrypt_secret,
encryptedSession
);
plugin.server.logger.debug("session data: %s", sessionPayload);
sessionPayload = JSON.parse(sessionPayload);
return sessionPayload;
}
async save_session(session_id, sessionPayload, ttl = null) {
const plugin = this;
const store = plugin.server.store;
await store.set(
SESSION_CACHE_PREFIX + session_id,
plugin.server.utils.encrypt(
plugin.server.secrets.session_encrypt_secret,
JSON.stringify(sessionPayload)
),
ttl
);
}
async update_session(session_id, sessionPayload) {
const plugin = this;
const store = plugin.server.store;
let ttl;
if (
plugin.config.features.session_expiry !== true &&
plugin.config.features.session_expiry > 0
) {
let sessionExpiresAt =
Date.now() / 1000 + plugin.config.features.session_expiry;
sessionExpiresAt = sessionExpiresAt * 1000;
if (sessionExpiresAt) {
sessionPayload.exp = Math.floor(sessionExpiresAt / 1000);
ttl = (sessionExpiresAt - Date.now()) / 1000;
}
plugin.server.logger.verbose("session TTL: %s", ttl);
}
await store.set(
SESSION_CACHE_PREFIX + session_id,
plugin.server.utils.encrypt(
plugin.server.secrets.session_encrypt_secret,
JSON.stringify(sessionPayload)
),
ttl
);
}
/**
* Generate appropriate authorization redirect URI
*
* We redirect to the exact same URI as requested (ensures we land at the same
* place) without the query original query params (prevents overwriting data).
*
* @param {*} uri
*/
get_authorization_redirect_uri(uri) {
const plugin = this;
const query = {};
query[HANDLER_INDICATOR_PARAM_NAME] = "authorization_callback";
if (plugin.config.redirect_uri) {
uri = plugin.config.redirect_uri;
}
const parsedURI = URI.parse(uri);
parsedURI.query = queryString.stringify(query);
return URI.serialize(parsedURI);
}
async prepare_token_headers(res, sessionData) {
const plugin = this;
if (sessionData.tokenSet.id_token) {
res.setHeader("X-Id-Token", sessionData.tokenSet.id_token);
}
if (sessionData.userinfo.data) {
res.setHeader("X-Userinfo", JSON.stringify(sessionData.userinfo.data));
}
if (sessionData.tokenSet.access_token) {
res.setHeader("X-Access-Token", sessionData.tokenSet.access_token);
}
if (
plugin.config.features.authorization_token &&
["id_token", "access_token", "refresh_token"].includes(
plugin.config.features.authorization_token
) &&
sessionData.tokenSet[plugin.config.features.authorization_token]
) {
res.setHeader(
"Authorization",
"Bearer " +
sessionData.tokenSet[plugin.config.features.authorization_token]
);
}
}
async prepare_authentication_data(res, sessionData) {
res.setAuthenticationData({
userinfo: sessionData.userinfo.data,
id_token: sessionData.tokenSet.id_token,
access_token: sessionData.tokenSet.access_token,
refresh_token: sessionData.tokenSet.refresh_token
});
}
is_redirectable_error(e) {
if (
e.error ||
(e.data && e.data.isResponseError) ||
(e.name && e.name == "OpenIdConnectError")
) {
if (e.data && e.data.isResponseError) {
e = e.data.payload;
}
switch (e.error) {
case "invalid_grant":
case "bad_verification_code":
return true;
case "incorrect_client_credentials":
case "redirect_uri_mismatch":
default:
return false;
}
}
return false;
}
async id_token_assertions(id_token) {
const plugin = this;
return await Assertion.assertSet(
id_token,
plugin.config.assertions.id_token
);
}
async userinfo_assertions(userinfo) {
const plugin = this;
return await Assertion.assertSet(
userinfo,
plugin.config.assertions.userinfo
);
}
async token_set_asertions(tokenSet) {
const plugin = this;
const client = await plugin.get_client();
const pluginStrategy =
plugin.constructor.name == "OpenIdConnectPlugin" ? "oidc" : "oauth2";
const PLUGIN_STRATEGY_OAUTH = "oauth";
const PLUGIN_STRATEGY_OIDC = "oidc";
/**
* token aud is the client_id
*/
if (
pluginStrategy == PLUGIN_STRATEGY_OIDC &&
plugin.config.assertions.aud &&
idToken.aud != plugin.config.client.client_id
) {
return false;
}
/**
* access token is expired and refresh tokens are disabled
*/
if (
plugin.config.assertions.exp &&
tokenset_is_expired(tokenSet) &&
!(
plugin.config.features.refresh_access_token &&
tokenset_can_refresh(tokenSet)
)
) {
plugin.server.logger.verbose(
"tokenSet is expired and refresh tokens disabled"
);
return false;
}
/**
* both access and refresh tokens are expired and refresh is enabled
*/
if (
plugin.config.assertions.exp &&
tokenset_is_expired(tokenSet) &&
plugin.config.features.refresh_access_token &&
!tokenset_can_refresh(tokenSet)
) {
plugin.server.logger.verbose(
"tokenSet expired and refresh no longer available"
);
return false;
}
if (
pluginStrategy == PLUGIN_STRATEGY_OIDC &&
plugin.config.assertions.nbf &&
tokenset_is_premature(tokenSet)
) {
plugin.server.logger.verbose("tokenSet is premature");
return false;
}
if (
pluginStrategy == PLUGIN_STRATEGY_OIDC &&
plugin.config.assertions.iss
) {
const issuer = await plugin.get_issuer();
if (!tokenset_issuer_match(tokenSet, issuer.issuer)) {
plugin.server.logger.verbose("tokenSet has a mismatch issuer");
return false;
}
}
if (
pluginStrategy == PLUGIN_STRATEGY_OIDC &&
plugin.config.features.introspect_access_token &&
tokenSet.access_token
) {
const issuer = await plugin.get_issuer();
if (!issuer.metadata.token_introspection_endpoint) {
plugin.server.logger.error("issuer does not support introspection");
throw new Error("issuer does not support introspection");
}
const response = await client.introspect(tokenSet.access_token);
plugin.server.logger.verbose("token introspect details %j", response);
if (response.active === false) {
plugin.server.logger.verbose("token no longer active!!!");
return false;
}
}
if (
pluginStrategy == PLUGIN_STRATEGY_OIDC &&
plugin.config.assertions.id_token
) {
let idToken;
idToken = jwt.decode(tokenSet.id_token);
let idTokenValid = await plugin.id_token_assertions(idToken);
if (!idTokenValid) {
return false;
}
}
return true;
}
log_userinfo(userinfo) {
const plugin = this;
plugin.server.logger.verbose("userinfo %j", userinfo);
}
log_token_set(tokenSet) {
const plugin = this;
if (tokenSet.refresh_token) {
plugin.server.logger.debug("refresh_token %j", tokenSet.refresh_token);
try {
plugin.server.logger.debug(
"refresh_token decoded %j",
jwt.decode(tokenSet.refresh_token)
);
} catch (e) {}
}
if (tokenSet.access_token) {
plugin.server.logger.debug("access_token %j", tokenSet.access_token);
try {
plugin.server.logger.debug(
"access_token decoded %j",
jwt.decode(tokenSet.access_token)
);
} catch (e) {}
}
if (tokenSet.id_token) {
const idToken = jwt.decode(tokenSet.id_token);
plugin.server.logger.debug("id_token %j", idToken);
}
}
}
/**
* https://github.com/lelylan/simple-oauth2
*/
class OauthPlugin extends BaseOauthPlugin {
/**
* Create new instance
*
* @name constructor
* @param {*} server
* @param {*} config
*/