lemonldap-ng-handler 0.9.6 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -6,7 +6,6 @@ import vm from 'vm';
6
6
  import crypto from 'crypto';
7
7
  import RE2 from 're2';
8
8
  import http from 'http';
9
- import normalizeUrl from 'normalize-url';
10
9
  import { getAccessTokenSessionId } from '@lemonldap-ng/jwt';
11
10
 
12
11
  /******************************************************************************
@@ -176,7 +175,11 @@ class HandlerInit {
176
175
  if (this.localConf.nodeVhosts === undefined)
177
176
  // istanbul ignore next
178
177
  throw new Error("No Virtualhosts configured for Node.js");
179
- this.vhostList = this.localConf.nodeVhosts.split(/[,\s]+/);
178
+ // Virtual host names are case-insensitive: keep them lower case, as the
179
+ // Host header is normalized the same way in resolveAlias()
180
+ this.vhostList = this.localConf.nodeVhosts
181
+ .split(/[,\s]+/)
182
+ .map((vhost) => vhost.toLowerCase());
180
183
  }
181
184
  reload() {
182
185
  return new Promise((resolve, reject) => {
@@ -212,7 +215,7 @@ class HandlerInit {
212
215
  const val = conf.vhostOptions[vhost][name];
213
216
  // @ts-ignore; k is in TSV type
214
217
  if (val > 0)
215
- this.tsv[k][vhost] = val;
218
+ this.tsv[k][vhost.toLowerCase()] = val;
216
219
  });
217
220
  }
218
221
  }
@@ -227,10 +230,11 @@ class HandlerInit {
227
230
  /**
228
231
  * Sessions storage initialization
229
232
  */
230
- //['global','oidc'].forEach
231
233
  if (!conf["globalStorage"] || !conf["globalStorageOptions"])
232
234
  // istanbul ignore next
233
235
  throw new Error("Missing session storage configuration");
236
+ this.tsv.sessionStorageModule = conf["globalStorage"];
237
+ this.tsv.sessionStorageOptions = conf["globalStorageOptions"];
234
238
  try {
235
239
  this.sessionAcc = new Session({
236
240
  storageModule: conf["globalStorage"],
@@ -243,44 +247,76 @@ class HandlerInit {
243
247
  cause: e,
244
248
  });
245
249
  }
250
+ /**
251
+ * OIDC/OAuth2 initialization (used by the OAuth2 handler type)
252
+ */
253
+ // Access token sessions are stored apart only when oidcStorage is
254
+ // set, else they share the global storage
255
+ if (conf.oidcStorage) {
256
+ this.tsv.oidcStorageModule = conf.oidcStorage;
257
+ this.tsv.oidcStorageOptions = conf.oidcStorageOptions || {};
258
+ }
259
+ else {
260
+ this.tsv.oidcStorageModule = conf["globalStorage"];
261
+ this.tsv.oidcStorageOptions = conf["globalStorageOptions"];
262
+ }
263
+ // Keep the client id of each relying party, exposed to rules and
264
+ // headers as $_clientId
265
+ this.tsv.oauth2Options = {};
266
+ Object.keys(conf.oidcRPMetaDataOptions || {}).forEach((rp) => {
267
+ var _a;
268
+ const clientId = (_a = conf.oidcRPMetaDataOptions[rp]) === null || _a === void 0 ? void 0 : _a.oidcRPMetaDataOptionsClientID;
269
+ // @ts-ignore: oauth2Options has just been initialized
270
+ if (clientId)
271
+ this.tsv.oauth2Options[rp] = { clientId };
272
+ });
246
273
  /**
247
274
  * Location rules initialization
248
275
  */
249
276
  Object.keys(conf.locationRules).forEach((vhost) => {
250
- if (this.vhostList.indexOf(vhost) == -1)
277
+ // Configuration keys are matched case-insensitively too
278
+ const name = vhost.toLowerCase();
279
+ if (this.vhostList.indexOf(name) == -1)
251
280
  return;
252
- this.tsv.locationCount[vhost] = 0;
281
+ this.tsv.locationCount[name] = 0;
253
282
  [
254
283
  "locationRegexp",
255
284
  "locationProtection",
256
285
  "locationCondition",
257
286
  ].forEach((k) => {
258
287
  // @ts-ignore: fields declared in TSV type
259
- if (this.tsv[k][vhost] === undefined)
260
- this.tsv[k][vhost] = [];
288
+ if (this.tsv[k][name] === undefined)
289
+ this.tsv[k][name] = [];
261
290
  });
262
- if (!this.safe[vhost])
263
- this.safe[vhost] = new SafeLib(conf);
291
+ if (!this.safe[name])
292
+ this.safe[name] = new SafeLib(conf);
264
293
  // @ts-ignore conf.locationRules[vhost] exists
265
294
  const rules = conf.locationRules[vhost];
266
295
  Object.keys(rules).forEach((url) => {
267
- const [cond, prot] = this.conditionSub(rules[url], this.safe[vhost]);
296
+ const [cond, prot] = this.conditionSub(rules[url], this.safe[name]);
268
297
  if (url === "default") {
269
- this.tsv.defaultCondition[vhost] = cond;
270
- this.tsv.defaultProtection[vhost] = prot;
298
+ this.tsv.defaultCondition[name] = cond;
299
+ this.tsv.defaultProtection[name] = prot;
271
300
  }
272
301
  else {
273
- this.tsv.locationCondition[vhost].push(cond);
274
- this.tsv.locationProtection[vhost].push(prot);
275
- this.tsv.locationRegexp[vhost].push(new RE2(url.replace(/\(\?#.*?\)/g, "")));
276
- this.tsv.locationCount[vhost]++;
302
+ this.tsv.locationCondition[name].push(cond);
303
+ this.tsv.locationProtection[name].push(prot);
304
+ this.tsv.locationRegexp[name].push(
305
+ // Rules are matched case-insensitively: a Node.js
306
+ // application often runs on a case-insensitive file
307
+ // system (macOS, Windows) or router, so "/ADMIN/SECRET"
308
+ // can serve the resource a "^/admin/secret" rule denies.
309
+ // A rule can opt out with "(?-i:...)", which RE2 honours
310
+ // inside a case-insensitive expression
311
+ new RE2(url.replace(/\(\?#.*?\)/g, ""), "i"));
312
+ this.tsv.locationCount[name]++;
277
313
  }
278
314
  });
279
- if (!this.tsv.defaultCondition[vhost]) {
315
+ if (!this.tsv.defaultCondition[name]) {
280
316
  // istanbul ignore next
281
- this.tsv.defaultCondition[vhost] = () => true;
317
+ this.tsv.defaultCondition[name] = () => true;
282
318
  // istanbul ignore next
283
- this.tsv.defaultProtection[vhost] = 0;
319
+ this.tsv.defaultProtection[name] = 0;
284
320
  }
285
321
  });
286
322
  /**
@@ -288,23 +324,24 @@ class HandlerInit {
288
324
  */
289
325
  if (conf.exportedHeaders !== undefined) {
290
326
  Object.keys(conf.exportedHeaders).forEach((vhost) => {
327
+ const name = vhost.toLowerCase();
291
328
  // @ts-ignore
292
329
  const headers = (
293
330
  // @ts-ignore: conf.exportedHeaders[vhost] is defined
294
331
  conf.exportedHeaders[vhost]);
295
- if (this.vhostList.indexOf(vhost) == -1)
332
+ if (this.vhostList.indexOf(name) == -1)
296
333
  return;
297
- if (!this.tsv.headerList[vhost])
298
- this.tsv.headerList[vhost] = [];
334
+ if (!this.tsv.headerList[name])
335
+ this.tsv.headerList[name] = [];
299
336
  let sub = "";
300
- Object.keys(headers).forEach((name) => {
301
- this.tsv.headerList[vhost].push(name);
302
- sub += `'${name}': ${this.substitute(headers[name])},`;
337
+ Object.keys(headers).forEach((header) => {
338
+ this.tsv.headerList[name].push(header);
339
+ sub += `'${header}': ${this.substitute(headers[header])},`;
303
340
  });
304
341
  sub = sub.replace(/,$/, "");
305
- vm.runInContext(`fg = function(session) {return {${sub}};}`, this.safe[vhost]);
342
+ vm.runInContext(`fg = function(session) {return {${sub}};}`, this.safe[name]);
306
343
  // @ts-ignore: fg is now defined
307
- this.tsv.forgeHeaders[vhost] = this.safe[vhost].fg;
344
+ this.tsv.forgeHeaders[name] = this.safe[name].fg;
308
345
  });
309
346
  }
310
347
  // TODO: post url initialization
@@ -317,7 +354,8 @@ class HandlerInit {
317
354
  if (conf.vhostOptions[vhost].aliases) {
318
355
  // @ts-ignore: conf.vhostOptions[vhost] is defined
319
356
  conf.vhostOptions[vhost].aliases.forEach((alias) => {
320
- this.tsv.vhostAlias[alias] = vhost;
357
+ this.tsv.vhostAlias[alias.toLowerCase()] =
358
+ vhost.toLowerCase();
321
359
  });
322
360
  }
323
361
  });
@@ -564,10 +602,175 @@ class HandlerInit {
564
602
  }
565
603
  }
566
604
 
605
+ /**
606
+ * Canonical form of an URI, as web servers do before routing requests to
607
+ * applications: the path is percent-decoded and normalized (duplicate slashes
608
+ * removed). The query string is left untouched since some rules contain GET
609
+ * parameters.
610
+ *
611
+ * This is a port of Lemonldap::NG::Handler::Main::canonicalUri(), with
612
+ * intentional differences for Node.js:
613
+ *
614
+ * - the path is decoded until it is stable, because an application or its
615
+ * framework may decode it more than once ("%252f");
616
+ * - a path containing "." or ".." segments, in its raw or decoded form, is
617
+ * rejected: Node.js routers (Express, Fastify, ...) do not normalize dot
618
+ * segments, so removing them here would make the handler decide on a path
619
+ * the application does not serve ("/admin/..%2Fpublic" would be seen as
620
+ * "/public" by the handler but routed under "/admin" by Express).
621
+ *
622
+ * Location rules must be matched against the path the protected application
623
+ * will serve, otherwise they can be bypassed with an encoded URL: the
624
+ * canonicalization used for CVE-2020-24660 did not decode "%2f", so a deny
625
+ * rule on "/admin/secret" missed "/admin%2fsecret".
626
+ */
627
+ const PERCENT_ENCODED = /(?:%[0-9A-Fa-f]{2})+/g;
628
+ /**
629
+ * Number of decoding passes: unlike a web server, an application (or the
630
+ * framework it runs on) may decode the path again, so "%252f" can be seen as
631
+ * "/" by the protected resource. Decoding stops as soon as nothing changes, so
632
+ * this bound only applies to deeply nested encodings. Each pass shortens the
633
+ * path, so the work stays linear in the length of the request URI.
634
+ */
635
+ const MAX_DECODE_PASSES = 5;
636
+ /**
637
+ * A "." or ".." path segment, whatever surrounds it.
638
+ */
639
+ const DOT_SEGMENT = /(?:^|\/)\.{1,2}(?:\/|$)/;
640
+ /**
641
+ * Raised when the request URI can not be matched safely against location rules.
642
+ */
643
+ class InvalidUriError extends Error {
644
+ constructor(uri) {
645
+ super("Invalid request URI");
646
+ this.uri = uri;
647
+ this.name = "InvalidUriError";
648
+ }
649
+ }
650
+ function assertNoDotSegment(path) {
651
+ if (DOT_SEGMENT.test(path))
652
+ throw new InvalidUriError(path);
653
+ }
654
+ /**
655
+ * Percent-decode a path like Perl's uri_unescape(): valid escape sequences are
656
+ * decoded, invalid ones are kept as is and "+" is left untouched.
657
+ */
658
+ function unescapeOnce(path) {
659
+ return path.replace(PERCENT_ENCODED, (encoded) => {
660
+ try {
661
+ return decodeURIComponent(encoded);
662
+ }
663
+ catch (_e) {
664
+ // Not valid UTF-8: decode bytes one by one (uri_unescape() returns raw
665
+ // bytes) so that the escapes do not survive decoding
666
+ return encoded.replace(/%([0-9A-Fa-f]{2})/g, (_match, hex) => String.fromCharCode(parseInt(hex, 16)));
667
+ }
668
+ });
669
+ }
670
+ /**
671
+ * Decode the path until it is stable. A dot segment produced by decoding is
672
+ * rejected: the application may see it even if the raw URI had none.
673
+ */
674
+ function unescapePath(path) {
675
+ for (let i = 0; i < MAX_DECODE_PASSES; i++) {
676
+ const decoded = unescapeOnce(path);
677
+ if (decoded === path)
678
+ break;
679
+ assertNoDotSegment(decoded);
680
+ path = decoded;
681
+ }
682
+ return path;
683
+ }
684
+ /**
685
+ * Request URI as sent by the client, restricted to its path and query: it
686
+ * identifies the resource for redirections, unlike the canonical URI that is
687
+ * only meant to be matched against rules.
688
+ */
689
+ function rawRequestUri(uri) {
690
+ if (!uri)
691
+ return "/";
692
+ // Absolute-URI form (RFC 7230 5.3.2): keep only the path and the query
693
+ const path = uri.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/, "");
694
+ return path.startsWith("/") ? path : "/";
695
+ }
696
+ /**
697
+ * @param uri URI to canonicalize
698
+ * @returns canonical URI
699
+ * @throws InvalidUriError if the URI can not be matched safely
700
+ */
701
+ function canonicalUri(uri) {
702
+ if (uri === undefined || uri === null)
703
+ return "/";
704
+ // Absolute-URI form (RFC 7230 5.3.2): applications only see the path
705
+ let path = uri.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?]*\/?/, "/");
706
+ // An empty path is "/" (RFC 3986 6.2.3)
707
+ if (/^(?:\?|$)/.test(path))
708
+ path = "/" + path;
709
+ let query;
710
+ const questionMark = path.indexOf("?");
711
+ if (questionMark >= 0) {
712
+ query = path.slice(questionMark + 1);
713
+ path = path.slice(0, questionMark);
714
+ }
715
+ // Only absolute paths are normalized, others (OPTIONS *, ...) are kept as is
716
+ if (path.startsWith("/")) {
717
+ assertNoDotSegment(path);
718
+ path = unescapePath(path);
719
+ // A "?" here can only come from a decoded "%3f" (the query string was
720
+ // split off the raw URI): keep it encoded, so that rule matching can not
721
+ // mistake it for the query separator
722
+ path = path.replace(/\?/g, "%3F");
723
+ // A path ending with "/" keeps its trailing slash
724
+ const trailingSlash = /\/$/.test(path);
725
+ const segments = path.split(/\/+/).filter((segment) => segment !== "");
726
+ path = "/" + segments.join("/");
727
+ if (trailingSlash && path !== "/")
728
+ path += "/";
729
+ }
730
+ return query === undefined ? path : `${path}?${query}`;
731
+ }
732
+
567
733
  /**
568
734
  * Default internal cache timeout in seconds
569
735
  */
570
736
  const DEFAULT_INTERNAL_CACHE_TIMEOUT = 15;
737
+ /**
738
+ * A Host header is a hostname (or an IP address) with an optional port. Any
739
+ * other value is refused: a Host header containing a path or a query would
740
+ * end up in the URLs built for redirections. Underscores are accepted because
741
+ * Docker Compose and some internal DNS use them.
742
+ */
743
+ const VALID_HOST = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?(?:\.[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?)*\.?)(?::[0-9]{1,5})?$/;
744
+ function isValidHost(host) {
745
+ return VALID_HOST.test(host);
746
+ }
747
+ /**
748
+ * A malformed request must not be redirected to the portal: answer with a
749
+ * plain 400.
750
+ */
751
+ function sendBadRequest(res) {
752
+ res.writeHead(400, "Bad request");
753
+ res.end();
754
+ }
755
+ /**
756
+ * Location rules are matched against the canonical URI. Rules can contain GET
757
+ * parameters, so the whole URI is tested first, but the path alone is tested
758
+ * too: an anchored rule such as "^/admin$" must still apply to "/admin?x=1",
759
+ * as it did when only the pathname was compared.
760
+ */
761
+ function ruleMatches(regex, uri) {
762
+ if (regex.test(uri))
763
+ return true;
764
+ const questionMark = uri.indexOf("?");
765
+ return questionMark > 0 && regex.test(uri.slice(0, questionMark));
766
+ }
767
+ /**
768
+ * Escape a user-controlled value before writing it in a log line: a decoded
769
+ * URI can contain CR/LF and forge fake log entries.
770
+ */
771
+ function logValue(value) {
772
+ return JSON.stringify(value);
773
+ }
571
774
  class LemonldapNGHandler extends HandlerInit {
572
775
  constructor() {
573
776
  super(...arguments);
@@ -583,16 +786,33 @@ class LemonldapNGHandler extends HandlerInit {
583
786
  * run(), the access control function
584
787
  */
585
788
  run(req, res, next) {
586
- const vhost = req.headers.host;
587
- if (vhost === undefined) {
588
- this.userLogger.error("Request without Host header");
589
- this.setError(res, "/", 400, "Bad request");
789
+ var _a;
790
+ /* 1 - get data */
791
+ const host = req.headers.host;
792
+ if (host === undefined || !isValidHost(host)) {
793
+ this.userLogger.error("Missing or invalid Host header");
794
+ sendBadRequest(res);
795
+ return;
796
+ }
797
+ const vhost = this.resolveAlias(req);
798
+ const rawUri = rawRequestUri(req.url);
799
+ let uri;
800
+ try {
801
+ uri = canonicalUri(req.url);
802
+ }
803
+ catch (e) {
804
+ if (e instanceof InvalidUriError) {
805
+ this.userLogger.warn(`Refusing malformed URI ${logValue(e.uri)}`);
806
+ }
807
+ else {
808
+ // istanbul ignore next
809
+ this.userLogger.error(`Unable to canonicalize URI: ${logValue(String(e))}`);
810
+ }
811
+ sendBadRequest(res);
590
812
  return;
591
813
  }
592
- /* 1 - get data */
593
- const uri = new URL(normalizeUrl(vhost + req.url)).pathname || "/";
594
814
  /* 2 - check for maintenance mode */
595
- if (this.tsv.maintenance[vhost])
815
+ if ((_a = this.tsv.maintenance[vhost]) !== null && _a !== void 0 ? _a : this.tsv.maintenance._)
596
816
  return this.setError(res, "/", 503, "Service Temporarily Unavailable");
597
817
  /* 3 - check if current URI is protected */
598
818
  const protection = this.isUnprotected(req, uri);
@@ -604,10 +824,13 @@ class LemonldapNGHandler extends HandlerInit {
604
824
  this.hideCookie(req);
605
825
  return next();
606
826
  }
607
- /* 4 - search for LLNG cookie */
608
- const id = this.fetchId(req);
609
- if (id !== "") {
610
- this.retrieveSession(id)
827
+ /* 4 - search for LLNG cookie (or any other credential, see subclasses) */
828
+ Promise.resolve(this.fetchId(req))
829
+ .then((id) => {
830
+ if (id === "") {
831
+ return this.goToPortal(res, this.selfUri(vhost, rawUri, host));
832
+ }
833
+ this.retrieveSession(id, req)
611
834
  .then((session) => {
612
835
  const user = session[this.tsv.whatToTrace];
613
836
  this.userLogger.debug(`User ${user} identified`);
@@ -617,11 +840,11 @@ class LemonldapNGHandler extends HandlerInit {
617
840
  this.sendHeaders(req, session);
618
841
  this.hideCookie(req);
619
842
  next();
620
- this.userLogger.info(`${vhost}: user ${user} was granted access to ${uri}`);
843
+ this.userLogger.info(`${logValue(vhost)}: user ${user} was granted access to ${logValue(uri)}`);
621
844
  }
622
845
  else {
623
846
  this.forbidden(req, res, session);
624
- this.userLogger.notice(`${vhost}: user ${user} was denied access to ${uri}`);
847
+ this.userLogger.notice(`${logValue(vhost)}: user ${user} was denied access to ${logValue(uri)}`);
625
848
  }
626
849
  })
627
850
  .catch((e) => {
@@ -631,17 +854,19 @@ class LemonldapNGHandler extends HandlerInit {
631
854
  })
632
855
  .catch((_e) => {
633
856
  /* Expired session */
634
- this.goToPortal(res, this.selfUri(vhost, uri));
857
+ this.goToPortal(res, this.selfUri(vhost, rawUri, host));
635
858
  });
636
- }
637
- else {
638
- this.goToPortal(res, this.selfUri(vhost, uri));
639
- }
859
+ })
860
+ // istanbul ignore next
861
+ .catch((e) => {
862
+ this.userLogger.error(`Unable to fetch session id: ${e}`);
863
+ this.goToPortal(res, this.selfUri(vhost, rawUri, host));
864
+ });
640
865
  }
641
- selfUri(vhost, uri) {
866
+ selfUri(vhost, uri, host = vhost) {
642
867
  return ((this.tsv.https && this.tsv.https[vhost] ? "https" : "http") +
643
868
  "://" +
644
- vhost +
869
+ host +
645
870
  uri);
646
871
  }
647
872
  nginxServer(fcgiOpt) {
@@ -687,16 +912,24 @@ class LemonldapNGHandler extends HandlerInit {
687
912
  if (!this.tsv.defaultCondition[vhost])
688
913
  return false;
689
914
  for (let i = 0; i < this.tsv.locationRegexp[vhost].length; i++) {
690
- if (this.tsv.locationRegexp[vhost][i].test(uri))
915
+ if (ruleMatches(this.tsv.locationRegexp[vhost][i], uri))
691
916
  return this.tsv.locationProtection[vhost][i];
692
917
  }
693
918
  return this.tsv.defaultProtection[vhost];
694
919
  }
695
920
  resolveAlias(req) {
696
- var _a;
697
- // @ts-ignore: req.headers.host has already been tested
698
- const vhost = (_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(":")[0];
699
- return vhost ? this.tsv.vhostAlias[vhost] || vhost : "undef";
921
+ // @ts-ignore: req.headers.host has already been validated
922
+ const host = req.headers.host;
923
+ if (!host)
924
+ return "undef";
925
+ // Host names are case-insensitive and may carry a port, IPv6 brackets and
926
+ // a trailing dot: "TEST1.EXAMPLE.COM.:443" designates "test1.example.com"
927
+ const vhost = host
928
+ .replace(/:\d+$/, "")
929
+ .replace(/^\[|\]$/g, "")
930
+ .replace(/\.$/, "")
931
+ .toLowerCase();
932
+ return this.tsv.vhostAlias[vhost] || vhost;
700
933
  }
701
934
  fetchId(req) {
702
935
  if (req.headers.cookie) {
@@ -706,7 +939,7 @@ class LemonldapNGHandler extends HandlerInit {
706
939
  }
707
940
  return "";
708
941
  }
709
- retrieveSession(id) {
942
+ retrieveSession(id, _req) {
710
943
  return new Promise((resolve, reject) => {
711
944
  if (this.sessionAcc === undefined)
712
945
  // istanbul ignore next
@@ -780,7 +1013,7 @@ class LemonldapNGHandler extends HandlerInit {
780
1013
  if (this.tsv.locationRegexp[vhost]) {
781
1014
  for (let i = 0; i < this.tsv.locationRegexp[vhost].length; i++) {
782
1015
  const regex = this.tsv.locationRegexp[vhost][i];
783
- if (regex.test(uri)) {
1016
+ if (ruleMatches(regex, uri)) {
784
1017
  return resolve(this.tsv.locationCondition[vhost][i](req, session));
785
1018
  }
786
1019
  }
@@ -840,8 +1073,10 @@ class LemonldapNGHandler extends HandlerInit {
840
1073
  }
841
1074
  const urlc = this.tsv.portal() +
842
1075
  (uri
843
- ? // @ts-ignore
844
- "?url=" + new Buffer.from(encodeURI(uri)).toString("base64")
1076
+ ? // As the Perl handler does, the URL is base64-encoded and then
1077
+ // percent-escaped (+ / = in the base64 alphabet); encoding the URL
1078
+ // itself would alter the resource the user is sent back to
1079
+ "?url=" + encodeURIComponent(Buffer.from(uri).toString("base64"))
845
1080
  : "") +
846
1081
  (args ? (uri ? "&" : "?") + args : "");
847
1082
  // req.redirect is defined when running under express. If not
@@ -911,6 +1146,8 @@ class LemonldapNGHandlerDevOps extends LemonldapNGHandler {
911
1146
  return new Promise((resolve, reject) => {
912
1147
  if (!lvOpts.lb)
913
1148
  vhost = lvOpts.host;
1149
+ // Virtual host names are case-insensitive, like the Host header
1150
+ vhost = vhost.toLowerCase();
914
1151
  delete lvOpts.lb;
915
1152
  lvOpts.headers = { Host: vhost };
916
1153
  const http = require(lvOpts.prot);
@@ -951,7 +1188,9 @@ class LemonldapNGHandlerDevOps extends LemonldapNGHandler {
951
1188
  else {
952
1189
  this.tsv.locationCondition[vhost].push(cond);
953
1190
  this.tsv.locationProtection[vhost].push(prot);
954
- this.tsv.locationRegexp[vhost].push(new RE2(url.replace(/\(\?#.*?\)/g, "")));
1191
+ this.tsv.locationRegexp[vhost].push(
1192
+ // See init.ts: rules are matched case-insensitively
1193
+ new RE2(url.replace(/\(\?#.*?\)/g, ""), "i"));
955
1194
  this.tsv.locationCount[vhost]++;
956
1195
  }
957
1196
  });
@@ -1039,109 +1278,420 @@ class LemonldapNGHandlerDevOpsST extends LemonldapNGHandlerDevOps {
1039
1278
 
1040
1279
  /**
1041
1280
  * OAuth2/OIDC Handler for LemonLDAP::NG
1042
- * Port of Lemonldap::NG::Handler::OAuth2
1281
+ * Port of Lemonldap::NG::Handler::Lib::OAuth2
1282
+ *
1283
+ * A Bearer access token is an *opaque credential*: the token itself (or the
1284
+ * `jti` claim of its JWT serialization) is the identifier of an access token
1285
+ * session created by the Portal. This handler therefore:
1043
1286
  *
1044
- * This handler validates OAuth2/OIDC access tokens and retrieves
1045
- * the associated session from the OIDC session storage.
1287
+ * 1. resolves the access token session in the OIDC session storage,
1288
+ * 2. follows it to the user session (or offline session) it was issued for,
1289
+ * 3. exposes the token attributes (scope, client, audiences, grant type) as
1290
+ * session attributes so that rules and headers can use them.
1291
+ *
1292
+ * Nothing but the session identifier is ever read from the token: the trust
1293
+ * anchor is the session store, not the token payload.
1046
1294
  */
1295
+ /* Prefix used by fetchId() to mark offline session ids */
1296
+ const OFFLINE_PREFIX = "O-";
1297
+ /**
1298
+ * Shape of a session identifier.
1299
+ *
1300
+ * The value carried by a Bearer token is attacker controlled and is handed
1301
+ * over as-is to the session storage, where some backends interpolate it into
1302
+ * a LDAP DN (@lemonldap-ng/session-ldap) or into an URL
1303
+ * (@lemonldap-ng/session-rest). Only accept what the Portal may have
1304
+ * generated, so that a crafted `jti` can not escape the lookup.
1305
+ */
1306
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]+$/;
1047
1307
  class LemonldapNGHandlerOAuth2 extends LemonldapNGHandler {
1308
+ constructor() {
1309
+ super(...arguments);
1310
+ this.ownOidcSessionAcc = false;
1311
+ this.state = new WeakMap();
1312
+ }
1048
1313
  /**
1049
- * Override init to also initialize OIDC session storage
1314
+ * Override reload() - and not init() - to set up the OIDC session storage.
1315
+ *
1316
+ * init() runs once, while reload() runs again on every configuration change
1317
+ * announced by the message broker, and it rebuilds the main session
1318
+ * accessor. The OIDC accessor must follow: else the handler would keep
1319
+ * querying the previous storage (with its own cache), localUnlog() would
1320
+ * only purge the new one, and a modified oidcStorage would never be applied.
1050
1321
  */
1051
- init() {
1052
- return new Promise((resolve, reject) => {
1053
- super
1054
- .init()
1055
- .then(() => {
1056
- // Initialize OIDC session storage if configured
1057
- if (this.tsv.oidcStorageModule) {
1058
- try {
1059
- this.oidcSessionAcc = new Session({
1060
- storageModule: this.tsv.oidcStorageModule,
1061
- storageModuleOptions: this.tsv.oidcStorageOptions || {},
1062
- });
1063
- this.oidcSessionAcc.ready
1064
- .then(() => {
1065
- this.userLogger.debug("OAuth2 OIDC session storage initialized");
1066
- resolve(true);
1067
- })
1068
- .catch((e) => {
1069
- this.userLogger.error(`Failed to initialize OIDC session storage: ${e}`);
1070
- reject(e);
1071
- });
1072
- }
1073
- catch (e) {
1074
- this.userLogger.error(`Failed to create OIDC session accessor: ${e}`);
1075
- reject(e);
1076
- }
1322
+ reload() {
1323
+ const _super = Object.create(null, {
1324
+ reload: { get: () => super.reload }
1325
+ });
1326
+ return __awaiter(this, void 0, void 0, function* () {
1327
+ const res = yield _super.reload.call(this);
1328
+ yield this.initOidcSessionStorage();
1329
+ return res;
1330
+ });
1331
+ }
1332
+ /**
1333
+ * (Re)build the accessor used for access token and offline sessions
1334
+ *
1335
+ * The new accessor is only installed once it is known to be usable: a
1336
+ * reload announcing a broken oidcStorage must leave the handler running on
1337
+ * its previous storage rather than answering 401 to every token, and must
1338
+ * not leak the accessor it failed to replace (its node-persist timers would
1339
+ * keep the process alive).
1340
+ */
1341
+ initOidcSessionStorage() {
1342
+ return __awaiter(this, void 0, void 0, function* () {
1343
+ const storageModule = this.tsv.oidcStorageModule;
1344
+ if (!storageModule) {
1345
+ // istanbul ignore next
1346
+ throw new Error("OAuth2 handler requires a session storage");
1347
+ }
1348
+ let candidate;
1349
+ let owned;
1350
+ // Reuse the main accessor when both storages are identical, as it is the
1351
+ // case when no dedicated oidcStorage is configured
1352
+ if (storageModule === this.tsv.sessionStorageModule &&
1353
+ JSON.stringify(this.tsv.oidcStorageOptions || {}) ===
1354
+ JSON.stringify(this.tsv.sessionStorageOptions || {})) {
1355
+ this.userLogger.debug("OAuth2 handler shares the main session storage");
1356
+ candidate = this.sessionAcc;
1357
+ owned = false;
1358
+ }
1359
+ else {
1360
+ try {
1361
+ candidate = new Session({
1362
+ storageModule,
1363
+ storageModuleOptions: this.tsv.oidcStorageOptions || {},
1364
+ });
1365
+ yield candidate.ready;
1077
1366
  }
1078
- else {
1079
- // Use default session storage for OIDC tokens
1080
- this.userLogger.debug("OAuth2 handler using default session storage for OIDC");
1081
- resolve(true);
1367
+ catch (e) {
1368
+ throw new Error(`Unable to load OIDC session module: ${e}`, {
1369
+ cause: e,
1370
+ });
1082
1371
  }
1083
- })
1084
- .catch(reject);
1372
+ owned = true;
1373
+ this.userLogger.debug("OAuth2 OIDC session storage initialized");
1374
+ }
1375
+ // Accessor built by a previous reload(), to be closed once replaced
1376
+ const previous = this.ownOidcSessionAcc ? this.oidcSessionAcc : undefined;
1377
+ this.oidcSessionAcc = candidate;
1378
+ this.ownOidcSessionAcc = owned;
1379
+ if (previous && previous !== candidate)
1380
+ yield previous.close();
1381
+ });
1382
+ }
1383
+ /**
1384
+ * Override localUnlog to purge the OIDC caches too
1385
+ *
1386
+ * When the Portal revokes an access token, it broadcasts an unlog/delSession
1387
+ * message holding the id of the deleted session. With a dedicated
1388
+ * oidcStorage, that session lives in the OIDC accessor, whose caches
1389
+ * Main::localUnlog() does not know about: the revoked token would keep
1390
+ * authenticating until the cache entry expires.
1391
+ * @param sessionId - Session ID to clear (uses last cached if not provided)
1392
+ */
1393
+ localUnlog(sessionId) {
1394
+ const _super = Object.create(null, {
1395
+ localUnlog: { get: () => super.localUnlog }
1085
1396
  });
1397
+ return __awaiter(this, void 0, void 0, function* () {
1398
+ // super.localUnlog() resets lastSessionId, read it first
1399
+ const id = sessionId || this.lastSessionId;
1400
+ yield _super.localUnlog.call(this, sessionId);
1401
+ // In the shared storage case both accessors are the same object, which
1402
+ // super.localUnlog() has already purged
1403
+ if (id && this.ownOidcSessionAcc && this.oidcSessionAcc) {
1404
+ yield this.oidcSessionAcc.clearAllCaches(id);
1405
+ }
1406
+ });
1407
+ }
1408
+ /**
1409
+ * Override run to bind the per-request state to both req and res: fetchId()
1410
+ * and retrieveSession() only see the request, goToPortal() only sees the
1411
+ * response.
1412
+ */
1413
+ run(req, res, next) {
1414
+ const state = {};
1415
+ this.state.set(req, state);
1416
+ this.state.set(res, state);
1417
+ return super.run(req, res, next);
1086
1418
  }
1087
1419
  /**
1088
- * Override fetchId to check for OAuth2 Bearer token
1420
+ * Override fetchId to resolve an OAuth2 Bearer token into a session id
1421
+ *
1422
+ * Contrary to the cookie case, the value carried by the request is *not* the
1423
+ * user session id: it identifies an access token session, which in turn
1424
+ * references the user session (or an offline session).
1089
1425
  * @param req - HTTP request
1090
1426
  */
1091
1427
  fetchId(req) {
1092
- // Check for Authorization header with Bearer token
1093
- const authHeader = req.headers.authorization;
1094
- if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
1095
- const accessToken = authHeader.substring(7).trim();
1096
- if (accessToken) {
1097
- // Try to extract session ID from the access token
1098
- const sessionId = getAccessTokenSessionId(accessToken);
1099
- if (sessionId) {
1100
- this.userLogger.debug(`OAuth2: extracted session ID from token`);
1101
- return sessionId;
1428
+ const _super = Object.create(null, {
1429
+ fetchId: { get: () => super.fetchId }
1430
+ });
1431
+ return __awaiter(this, void 0, void 0, function* () {
1432
+ const authHeader = req.headers.authorization;
1433
+ if (!authHeader || !/^bearer\s/i.test(authHeader)) {
1434
+ // Fall back to cookie-based authentication
1435
+ return _super.fetchId.call(this, req);
1436
+ }
1437
+ const accessToken = authHeader.replace(/^bearer\s+/i, "").trim();
1438
+ // An empty Bearer token carries no credential, but the request may still
1439
+ // hold a valid cookie: the Perl handler reaches Main::fetchId here
1440
+ if (!accessToken) {
1441
+ this.userLogger.info("OAuth2: empty Bearer token");
1442
+ return this.fallbackToCookie(req);
1443
+ }
1444
+ // The token is either the access token session id, or a JWT whose `jti`
1445
+ // claim holds it
1446
+ const accessTokenId = getAccessTokenSessionId(accessToken);
1447
+ if (!accessTokenId) {
1448
+ return this.invalidToken(req, "No session id found in access token");
1449
+ }
1450
+ // The token is not signed, and even a signed one is not trusted here: the
1451
+ // id is about to be given to the session storage, so refuse anything that
1452
+ // does not look like a session id
1453
+ if (!this.isSessionId(accessTokenId)) {
1454
+ return this.invalidToken(req, "Malformed access token session id");
1455
+ }
1456
+ const lookup = yield this.getOIDCInfos(accessTokenId);
1457
+ // An expired or corrupted access token session is a hard failure
1458
+ if (lookup.status === "invalid") {
1459
+ return this.invalidToken(req, "Access token session is not usable");
1460
+ }
1461
+ // An unknown access token is not necessarily an attack: the request may
1462
+ // also carry a valid cookie. Behave as the Perl handler and fall back.
1463
+ if (lookup.status === "notFound") {
1464
+ this.userLogger.info(`Unknown access token session ${accessTokenId}`);
1465
+ return this.fallbackToCookie(req);
1466
+ }
1467
+ const infos = lookup.data;
1468
+ // Scope, client and audiences, to be exposed as session attributes. They
1469
+ // are only published once the token is known to grant a session: a token
1470
+ // that ends up on the cookie fallback below must not lend its scope to
1471
+ // the session the cookie points to. This diverges from the Perl handler,
1472
+ // which sets $req->data->{_scope} before falling back and therefore lets
1473
+ // a bare client credentials token satisfy a $_scope based rule.
1474
+ const attrs = infos.rp
1475
+ ? this.tokenAttributes(accessToken, infos)
1476
+ : undefined;
1477
+ // Token tied to a regular session
1478
+ if (infos.user_session_id) {
1479
+ if (!this.isSessionId(infos.user_session_id)) {
1480
+ return this.invalidToken(req, `Malformed user_session_id in access token session ${accessTokenId}`);
1102
1481
  }
1103
- else {
1104
- this.userLogger.warn("OAuth2: could not extract session ID from token");
1105
- return "";
1482
+ const state = this.stateFor(req);
1483
+ state.viaToken = true;
1484
+ state.attrs = attrs;
1485
+ this.userLogger.debug(`OAuth2: get user session ${infos.user_session_id}`);
1486
+ return infos.user_session_id;
1487
+ }
1488
+ // Token tied to an offline session
1489
+ if (infos.offline_session_id) {
1490
+ if (!this.isSessionId(infos.offline_session_id)) {
1491
+ return this.invalidToken(req, `Malformed offline_session_id in access token session ${accessTokenId}`);
1106
1492
  }
1493
+ const state = this.stateFor(req);
1494
+ state.viaToken = true;
1495
+ state.attrs = attrs;
1496
+ this.userLogger.debug(`OAuth2: get offline session ${infos.offline_session_id}`);
1497
+ return `${OFFLINE_PREFIX}${infos.offline_session_id}`;
1107
1498
  }
1108
- }
1109
- // Fall back to cookie-based authentication
1110
- return super.fetchId(req);
1499
+ this.userLogger.warn(`Access token session ${accessTokenId} references no session`);
1500
+ return this.fallbackToCookie(req);
1501
+ });
1111
1502
  }
1112
1503
  /**
1113
- * Override retrieveSession to use OIDC session storage if token-based
1114
- * @param id - Session ID
1504
+ * Override retrieveSession to handle offline sessions and to expose the
1505
+ * access token attributes to rules and headers
1506
+ * @param id - Session ID, prefixed by "O-" for offline sessions
1507
+ * @param req - HTTP request, when available
1115
1508
  */
1116
- retrieveSession(id) {
1117
- // Check if we should use OIDC session storage
1118
- // For now, use the same logic as parent class
1119
- // The OIDC sessions are typically in the same format
1120
- if (this.oidcSessionAcc) {
1121
- return new Promise((resolve, reject) => {
1122
- // @ts-ignore: oidcSessionAcc is defined
1123
- this.oidcSessionAcc
1124
- .get(id)
1125
- .then((session) => {
1126
- const now = (Date.now() / 1000) | 0;
1127
- if (now - session._utime > this.tsv.timeout ||
1128
- (this.tsv.timeoutActivity &&
1129
- session._lastSeen &&
1130
- // @ts-ignore: session._lastSeen is defined
1131
- now - session._lastSeen > this.tsv.timeoutActivity)) {
1132
- reject(`OAuth2 session ${id} expired`);
1133
- }
1134
- else {
1135
- resolve(session);
1136
- }
1137
- })
1138
- .catch((_e) => {
1139
- // If not found in OIDC storage, try main storage
1140
- super.retrieveSession(id).then(resolve).catch(reject);
1141
- });
1509
+ retrieveSession(id, req) {
1510
+ var _a;
1511
+ const attrs = req ? (_a = this.state.get(req)) === null || _a === void 0 ? void 0 : _a.attrs : undefined;
1512
+ if (!id.startsWith(OFFLINE_PREFIX)) {
1513
+ return super.retrieveSession(id, req).then((session) => this.withTokenAttributes(session, attrs), (e) => {
1514
+ var _a;
1515
+ if (req && ((_a = this.state.get(req)) === null || _a === void 0 ? void 0 : _a.viaToken)) {
1516
+ this.stateFor(req).error = "invalid_token";
1517
+ }
1518
+ throw e;
1142
1519
  });
1143
1520
  }
1144
- return super.retrieveSession(id);
1521
+ // Offline sessions live in the OIDC storage
1522
+ const offlineId = id.substring(OFFLINE_PREFIX.length);
1523
+ return this.getOIDCInfos(offlineId).then((lookup) => {
1524
+ if (lookup.status !== "ok") {
1525
+ if (req)
1526
+ this.stateFor(req).error = "invalid_token";
1527
+ throw `Offline session ${offlineId} can not be retrieved`;
1528
+ }
1529
+ return this.withTokenAttributes(lookup.data, attrs);
1530
+ },
1531
+ // istanbul ignore next
1532
+ (e) => {
1533
+ if (req)
1534
+ this.stateFor(req).error = "invalid_token";
1535
+ throw e;
1536
+ });
1537
+ }
1538
+ /**
1539
+ * Hide the access token from the protected application
1540
+ * @param req - HTTP request
1541
+ */
1542
+ hideCookie(req) {
1543
+ if (req.headers.authorization) {
1544
+ this.userLogger.debug("OAuth2: removing Authorization header");
1545
+ delete req.headers.authorization;
1546
+ }
1547
+ super.hideCookie(req);
1548
+ }
1549
+ /**
1550
+ * A resource server never redirects: answer with a 401 and the challenge
1551
+ * described in RFC 6750 section 3
1552
+ * @param res - HTTP response
1553
+ * @param _uri - Original URI (unused)
1554
+ * @param _args - Additional arguments (unused)
1555
+ */
1556
+ goToPortal(res, _uri, _args = "") {
1557
+ var _a;
1558
+ const error = (_a = this.state.get(res)) === null || _a === void 0 ? void 0 : _a.error;
1559
+ res.setHeader("WWW-Authenticate", "Bearer" + (error ? ` error="${error}"` : ""));
1560
+ // res.status is defined when running under express. If not we are running
1561
+ // as FastCGI server
1562
+ // @ts-ignore: res.status may exist
1563
+ if (res.status) {
1564
+ // @ts-ignore: res.status may exist
1565
+ res.status(401).send("Unauthorized");
1566
+ }
1567
+ else {
1568
+ res.writeHead(401, "Unauthorized");
1569
+ }
1570
+ }
1571
+ /**
1572
+ * Close the dedicated OIDC session storage, if any
1573
+ */
1574
+ stopEventLoop() {
1575
+ const _super = Object.create(null, {
1576
+ stopEventLoop: { get: () => super.stopEventLoop }
1577
+ });
1578
+ return __awaiter(this, void 0, void 0, function* () {
1579
+ yield _super.stopEventLoop.call(this);
1580
+ if (this.ownOidcSessionAcc && this.oidcSessionAcc) {
1581
+ yield this.oidcSessionAcc.close();
1582
+ this.userLogger.debug("OIDC session storage closed");
1583
+ }
1584
+ });
1585
+ }
1586
+ /**
1587
+ * Get a session from the OIDC storage and check that it is not expired
1588
+ *
1589
+ * Note: the session backends do not tell an unknown session apart from an
1590
+ * unreachable storage, so both end up as "notFound" here, exactly as in the
1591
+ * Perl handler and as in the cookie path of Handler::Main. A storage outage
1592
+ * is therefore reported to the client as an invalid token. Fixing this
1593
+ * requires a "not found" signal in every @lemonldap-ng/session-* backend.
1594
+ * @param id - Access token, offline or OIDC session id
1595
+ */
1596
+ getOIDCInfos(id) {
1597
+ if (this.oidcSessionAcc === undefined) {
1598
+ // istanbul ignore next
1599
+ return Promise.resolve({ status: "invalid" });
1600
+ }
1601
+ return this.oidcSessionAcc.get(id).then((data) => {
1602
+ // A non numeric _utime would turn the comparison below into
1603
+ // `NaN > timeout`, i.e. false, and grant an unbounded lifetime
1604
+ const utime = Number(data._utime);
1605
+ if (!data._utime || !Number.isFinite(utime)) {
1606
+ this.userLogger.error(`_utime missing from OIDC session ${id}`);
1607
+ return { status: "invalid" };
1608
+ }
1609
+ const now = (Date.now() / 1000) | 0;
1610
+ if (now - utime > this.tsv.timeout) {
1611
+ this.userLogger.info(`OIDC session ${id} expired`);
1612
+ return { status: "invalid" };
1613
+ }
1614
+ this.userLogger.debug(`Get OIDC session ${id}`);
1615
+ return { status: "ok", data };
1616
+ }, (e) => {
1617
+ this.userLogger.info(`OIDC session ${id} can not be retrieved: ${e}`);
1618
+ return { status: "notFound" };
1619
+ });
1620
+ }
1621
+ /**
1622
+ * Collect the access token session fields exposed to rules and headers
1623
+ * @param accessToken - Bearer token, as received
1624
+ * @param infos - Access token session
1625
+ */
1626
+ tokenAttributes(accessToken, infos) {
1627
+ var _a, _b;
1628
+ const attrs = {
1629
+ _accessToken: accessToken,
1630
+ _clientConfKey: infos.rp,
1631
+ };
1632
+ if (infos.scope !== undefined)
1633
+ attrs._scope = infos.scope;
1634
+ if (infos.grant_type !== undefined) {
1635
+ attrs._oidc_grant_type = infos.grant_type;
1636
+ }
1637
+ if (infos.aud !== undefined)
1638
+ attrs._audiences = infos.aud;
1639
+ const clientId = (_b = (_a = this.tsv.oauth2Options) === null || _a === void 0 ? void 0 : _a[infos.rp]) === null || _b === void 0 ? void 0 : _b.clientId;
1640
+ if (clientId)
1641
+ attrs._clientId = clientId;
1642
+ return attrs;
1643
+ }
1644
+ /**
1645
+ * Build a copy of the session enriched with the access token attributes.
1646
+ * A copy is mandatory: the session object may be shared with the session
1647
+ * caches.
1648
+ */
1649
+ withTokenAttributes(session, attrs) {
1650
+ return attrs ? Object.assign(Object.assign({}, session), attrs) : session;
1651
+ }
1652
+ /**
1653
+ * Check that a value may be handed over to the session storage
1654
+ *
1655
+ * Applied both to the id carried by the token and to the ids read from the
1656
+ * access token session: the latter are written by the Portal, but they end
1657
+ * up in a LDAP DN or in an URL just the same.
1658
+ * @param id - Candidate session id
1659
+ */
1660
+ isSessionId(id) {
1661
+ return typeof id === "string" && SESSION_ID_RE.test(id);
1662
+ }
1663
+ /**
1664
+ * Get (or create) the state attached to a request or a response
1665
+ */
1666
+ stateFor(o) {
1667
+ let state = this.state.get(o);
1668
+ if (!state) {
1669
+ state = {};
1670
+ this.state.set(o, state);
1671
+ }
1672
+ return state;
1673
+ }
1674
+ /**
1675
+ * Reject the request with an "invalid_token" OAuth2 error
1676
+ */
1677
+ invalidToken(req, msg) {
1678
+ this.userLogger.warn(`OAuth2: ${msg}`);
1679
+ this.stateFor(req).error = "invalid_token";
1680
+ return "";
1681
+ }
1682
+ /**
1683
+ * Use the LLNG cookie when the Bearer token can not be resolved
1684
+ */
1685
+ fallbackToCookie(req) {
1686
+ const _super = Object.create(null, {
1687
+ fetchId: { get: () => super.fetchId }
1688
+ });
1689
+ return __awaiter(this, void 0, void 0, function* () {
1690
+ const id = yield _super.fetchId.call(this, req);
1691
+ if (id === "")
1692
+ this.stateFor(req).error = "invalid_token";
1693
+ return id;
1694
+ });
1145
1695
  }
1146
1696
  }
1147
1697