@backstage/backend-test-utils 0.3.3 → 0.3.4-next.2

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/dist/index.cjs.js CHANGED
@@ -13,8 +13,9 @@ var textextensions = require('textextensions');
13
13
  var path = require('path');
14
14
  var backendAppApi = require('@backstage/backend-app-api');
15
15
  var backendPluginApi = require('@backstage/backend-plugin-api');
16
- var express = require('express');
17
16
  var errors = require('@backstage/errors');
17
+ var cookie = require('cookie');
18
+ var express = require('express');
18
19
 
19
20
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
20
21
 
@@ -74,7 +75,7 @@ async function startMysqlContainer(image) {
74
75
  const user = "root";
75
76
  const password = uuid.v4();
76
77
  const { GenericContainer } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('testcontainers')); });
77
- const container = await new GenericContainer(image).withExposedPorts(3306).withEnv("MYSQL_ROOT_PASSWORD", password).withTmpFs({ "/var/lib/mysql": "rw" }).start();
78
+ const container = await new GenericContainer(image).withExposedPorts(3306).withEnvironment({ MYSQL_ROOT_PASSWORD: password }).withTmpFs({ "/var/lib/mysql": "rw" }).start();
78
79
  const host = container.getHost();
79
80
  const port = container.getMappedPort(3306);
80
81
  const stop = async () => {
@@ -112,7 +113,7 @@ async function startPostgresContainer(image) {
112
113
  const user = "postgres";
113
114
  const password = uuid.v4();
114
115
  const { GenericContainer } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('testcontainers')); });
115
- const container = await new GenericContainer(image).withExposedPorts(5432).withEnv("POSTGRES_PASSWORD", password).withTmpFs({ "/var/lib/postgresql/data": "rw" }).start();
116
+ const container = await new GenericContainer(image).withExposedPorts(5432).withEnvironment({ POSTGRES_PASSWORD: password }).withTmpFs({ "/var/lib/postgresql/data": "rw" }).start();
116
117
  const host = container.getHost();
117
118
  const port = container.getMappedPort(5432);
118
119
  const stop = async () => {
@@ -181,10 +182,10 @@ const allDatabases = Object.freeze({
181
182
  }
182
183
  });
183
184
 
184
- var __defProp$1 = Object.defineProperty;
185
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
186
- var __publicField$1 = (obj, key, value) => {
187
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
185
+ var __defProp$3 = Object.defineProperty;
186
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
187
+ var __publicField$3 = (obj, key, value) => {
188
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
188
189
  return value;
189
190
  };
190
191
  const LARGER_POOL_CONFIG = {
@@ -195,8 +196,8 @@ const LARGER_POOL_CONFIG = {
195
196
  };
196
197
  const _TestDatabases = class _TestDatabases {
197
198
  constructor(supportedIds) {
198
- __publicField$1(this, "instanceById");
199
- __publicField$1(this, "supportedIds");
199
+ __publicField$3(this, "instanceById");
200
+ __publicField$3(this, "supportedIds");
200
201
  this.instanceById = /* @__PURE__ */ new Map();
201
202
  this.supportedIds = supportedIds;
202
203
  }
@@ -431,7 +432,7 @@ const _TestDatabases = class _TestDatabases {
431
432
  }
432
433
  }
433
434
  };
434
- __publicField$1(_TestDatabases, "defaultIds");
435
+ __publicField$3(_TestDatabases, "defaultIds");
435
436
  let TestDatabases = _TestDatabases;
436
437
 
437
438
  function setupRequestMockHandlers(worker) {
@@ -440,63 +441,63 @@ function setupRequestMockHandlers(worker) {
440
441
  afterEach(() => worker.resetHandlers());
441
442
  }
442
443
 
443
- var __defProp = Object.defineProperty;
444
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
445
- var __publicField = (obj, key, value) => {
446
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
444
+ var __defProp$2 = Object.defineProperty;
445
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
446
+ var __publicField$2 = (obj, key, value) => {
447
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
447
448
  return value;
448
449
  };
449
- var __accessCheck$4 = (obj, member, msg) => {
450
+ var __accessCheck$5 = (obj, member, msg) => {
450
451
  if (!member.has(obj))
451
452
  throw TypeError("Cannot " + msg);
452
453
  };
453
- var __privateGet$4 = (obj, member, getter) => {
454
- __accessCheck$4(obj, member, "read from private field");
454
+ var __privateGet$5 = (obj, member, getter) => {
455
+ __accessCheck$5(obj, member, "read from private field");
455
456
  return getter ? getter.call(obj) : member.get(obj);
456
457
  };
457
- var __privateAdd$4 = (obj, member, value) => {
458
+ var __privateAdd$5 = (obj, member, value) => {
458
459
  if (member.has(obj))
459
460
  throw TypeError("Cannot add the same private member more than once");
460
461
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
461
462
  };
462
- var __privateSet$4 = (obj, member, value, setter) => {
463
- __accessCheck$4(obj, member, "write to private field");
463
+ var __privateSet$5 = (obj, member, value, setter) => {
464
+ __accessCheck$5(obj, member, "write to private field");
464
465
  setter ? setter.call(obj, value) : member.set(obj, value);
465
466
  return value;
466
467
  };
467
- var __privateMethod$3 = (obj, member, method) => {
468
- __accessCheck$4(obj, member, "access private method");
468
+ var __privateMethod$4 = (obj, member, method) => {
469
+ __accessCheck$5(obj, member, "access private method");
469
470
  return method;
470
471
  };
471
472
  var _root, _transformInput, transformInput_fn;
472
473
  const tmpdirMarker = Symbol("os-tmpdir-mock");
473
474
  class MockDirectoryImpl {
474
475
  constructor(root) {
475
- __privateAdd$4(this, _transformInput);
476
- __privateAdd$4(this, _root, void 0);
477
- __publicField(this, "clear", () => {
476
+ __privateAdd$5(this, _transformInput);
477
+ __privateAdd$5(this, _root, void 0);
478
+ __publicField$2(this, "clear", () => {
478
479
  this.setContent({});
479
480
  });
480
- __publicField(this, "remove", () => {
481
- fs__default["default"].rmSync(__privateGet$4(this, _root), { recursive: true, force: true, maxRetries: 10 });
481
+ __publicField$2(this, "remove", () => {
482
+ fs__default["default"].rmSync(__privateGet$5(this, _root), { recursive: true, force: true, maxRetries: 10 });
482
483
  });
483
- __privateSet$4(this, _root, root);
484
+ __privateSet$5(this, _root, root);
484
485
  }
485
486
  get path() {
486
- return __privateGet$4(this, _root);
487
+ return __privateGet$5(this, _root);
487
488
  }
488
489
  resolve(...paths) {
489
- return path.resolve(__privateGet$4(this, _root), ...paths);
490
+ return path.resolve(__privateGet$5(this, _root), ...paths);
490
491
  }
491
492
  setContent(root) {
492
493
  this.remove();
493
494
  return this.addContent(root);
494
495
  }
495
496
  addContent(root) {
496
- const entries = __privateMethod$3(this, _transformInput, transformInput_fn).call(this, root);
497
+ const entries = __privateMethod$4(this, _transformInput, transformInput_fn).call(this, root);
497
498
  for (const entry of entries) {
498
- const fullPath = path.resolve(__privateGet$4(this, _root), entry.path);
499
- if (!backendCommon.isChildPath(__privateGet$4(this, _root), fullPath)) {
499
+ const fullPath = path.resolve(__privateGet$5(this, _root), entry.path);
500
+ if (!backendCommon.isChildPath(__privateGet$5(this, _root), fullPath)) {
500
501
  throw new Error(
501
502
  `Provided path must resolve to a child path of the mock directory, got '${fullPath}'`
502
503
  );
@@ -520,8 +521,8 @@ class MockDirectoryImpl {
520
521
  content(options) {
521
522
  var _a, _b;
522
523
  const shouldReadAsText = (_a = typeof (options == null ? void 0 : options.shouldReadAsText) === "boolean" ? () => options == null ? void 0 : options.shouldReadAsText : options == null ? void 0 : options.shouldReadAsText) != null ? _a : (path$1) => textextensions__default["default"].includes(path.extname(path$1).slice(1));
523
- const root = path.resolve(__privateGet$4(this, _root), (_b = options == null ? void 0 : options.path) != null ? _b : "");
524
- if (!backendCommon.isChildPath(__privateGet$4(this, _root), root)) {
524
+ const root = path.resolve(__privateGet$5(this, _root), (_b = options == null ? void 0 : options.path) != null ? _b : "");
525
+ if (!backendCommon.isChildPath(__privateGet$5(this, _root), root)) {
525
526
  throw new Error(
526
527
  `Provided path must resolve to a child path of the mock directory, got '${root}'`
527
528
  );
@@ -622,26 +623,26 @@ class MockIdentityService {
622
623
  }
623
624
  }
624
625
 
625
- var __accessCheck$3 = (obj, member, msg) => {
626
+ var __accessCheck$4 = (obj, member, msg) => {
626
627
  if (!member.has(obj))
627
628
  throw TypeError("Cannot " + msg);
628
629
  };
629
- var __privateGet$3 = (obj, member, getter) => {
630
- __accessCheck$3(obj, member, "read from private field");
630
+ var __privateGet$4 = (obj, member, getter) => {
631
+ __accessCheck$4(obj, member, "read from private field");
631
632
  return getter ? getter.call(obj) : member.get(obj);
632
633
  };
633
- var __privateAdd$3 = (obj, member, value) => {
634
+ var __privateAdd$4 = (obj, member, value) => {
634
635
  if (member.has(obj))
635
636
  throw TypeError("Cannot add the same private member more than once");
636
637
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
637
638
  };
638
- var __privateSet$3 = (obj, member, value, setter) => {
639
- __accessCheck$3(obj, member, "write to private field");
639
+ var __privateSet$4 = (obj, member, value, setter) => {
640
+ __accessCheck$4(obj, member, "write to private field");
640
641
  setter ? setter.call(obj, value) : member.set(obj, value);
641
642
  return value;
642
643
  };
643
- var __privateMethod$2 = (obj, member, method) => {
644
- __accessCheck$3(obj, member, "access private method");
644
+ var __privateMethod$3 = (obj, member, method) => {
645
+ __accessCheck$4(obj, member, "access private method");
645
646
  return method;
646
647
  };
647
648
  var _level, _meta, _log, log_fn;
@@ -654,11 +655,11 @@ const levels = {
654
655
  };
655
656
  const _MockRootLoggerService = class _MockRootLoggerService {
656
657
  constructor(level, meta) {
657
- __privateAdd$3(this, _log);
658
- __privateAdd$3(this, _level, void 0);
659
- __privateAdd$3(this, _meta, void 0);
660
- __privateSet$3(this, _level, level);
661
- __privateSet$3(this, _meta, meta);
658
+ __privateAdd$4(this, _log);
659
+ __privateAdd$4(this, _level, void 0);
660
+ __privateAdd$4(this, _meta, void 0);
661
+ __privateSet$4(this, _level, level);
662
+ __privateSet$4(this, _meta, meta);
662
663
  }
663
664
  static create(options) {
664
665
  var _a;
@@ -669,19 +670,19 @@ const _MockRootLoggerService = class _MockRootLoggerService {
669
670
  return new _MockRootLoggerService(levels[level], {});
670
671
  }
671
672
  error(message, meta) {
672
- __privateMethod$2(this, _log, log_fn).call(this, "error", message, meta);
673
+ __privateMethod$3(this, _log, log_fn).call(this, "error", message, meta);
673
674
  }
674
675
  warn(message, meta) {
675
- __privateMethod$2(this, _log, log_fn).call(this, "warn", message, meta);
676
+ __privateMethod$3(this, _log, log_fn).call(this, "warn", message, meta);
676
677
  }
677
678
  info(message, meta) {
678
- __privateMethod$2(this, _log, log_fn).call(this, "info", message, meta);
679
+ __privateMethod$3(this, _log, log_fn).call(this, "info", message, meta);
679
680
  }
680
681
  debug(message, meta) {
681
- __privateMethod$2(this, _log, log_fn).call(this, "debug", message, meta);
682
+ __privateMethod$3(this, _log, log_fn).call(this, "debug", message, meta);
682
683
  }
683
684
  child(meta) {
684
- return new _MockRootLoggerService(__privateGet$3(this, _level), { ...__privateGet$3(this, _meta), ...meta });
685
+ return new _MockRootLoggerService(__privateGet$4(this, _level), { ...__privateGet$4(this, _meta), ...meta });
685
686
  }
686
687
  };
687
688
  _level = new WeakMap();
@@ -690,13 +691,380 @@ _log = new WeakSet();
690
691
  log_fn = function(level, message, meta) {
691
692
  var _a;
692
693
  const levelValue = (_a = levels[level]) != null ? _a : 0;
693
- if (levelValue <= __privateGet$3(this, _level)) {
694
- const labels = Object.entries(__privateGet$3(this, _meta)).map(([key, value]) => `${key}=${value}`).join(",");
694
+ if (levelValue <= __privateGet$4(this, _level)) {
695
+ const labels = Object.entries(__privateGet$4(this, _meta)).map(([key, value]) => `${key}=${value}`).join(",");
695
696
  console[level](`${labels} ${message}`, meta);
696
697
  }
697
698
  };
698
699
  let MockRootLoggerService = _MockRootLoggerService;
699
700
 
701
+ const DEFAULT_MOCK_USER_ENTITY_REF = "user:default/mock";
702
+ const DEFAULT_MOCK_SERVICE_SUBJECT = "external:test-service";
703
+ const MOCK_AUTH_COOKIE = "backstage-auth";
704
+ const MOCK_NONE_TOKEN = "mock-none-token";
705
+ const MOCK_USER_TOKEN = "mock-user-token";
706
+ const MOCK_USER_TOKEN_PREFIX = "mock-user-token:";
707
+ const MOCK_INVALID_USER_TOKEN = "mock-invalid-user-token";
708
+ const MOCK_USER_LIMITED_TOKEN_PREFIX = "mock-limited-user-token:";
709
+ const MOCK_INVALID_USER_LIMITED_TOKEN = "mock-invalid-limited-user-token";
710
+ const MOCK_SERVICE_TOKEN = "mock-service-token";
711
+ const MOCK_SERVICE_TOKEN_PREFIX = "mock-service-token:";
712
+ const MOCK_INVALID_SERVICE_TOKEN = "mock-invalid-service-token";
713
+ function validateUserEntityRef(ref) {
714
+ if (!ref.match(/^.+:.+\/.+$/)) {
715
+ throw new TypeError(
716
+ `Invalid user entity reference '${ref}', expected <kind>:<namespace>/<name>`
717
+ );
718
+ }
719
+ }
720
+ exports.mockCredentials = void 0;
721
+ ((mockCredentials2) => {
722
+ function none() {
723
+ return {
724
+ $$type: "@backstage/BackstageCredentials",
725
+ principal: { type: "none" }
726
+ };
727
+ }
728
+ mockCredentials2.none = none;
729
+ ((none2) => {
730
+ function header() {
731
+ return `Bearer ${MOCK_NONE_TOKEN}`;
732
+ }
733
+ none2.header = header;
734
+ })(none = mockCredentials2.none || (mockCredentials2.none = {}));
735
+ function user(userEntityRef = DEFAULT_MOCK_USER_ENTITY_REF) {
736
+ validateUserEntityRef(userEntityRef);
737
+ return {
738
+ $$type: "@backstage/BackstageCredentials",
739
+ principal: { type: "user", userEntityRef }
740
+ };
741
+ }
742
+ mockCredentials2.user = user;
743
+ ((user2) => {
744
+ function token(userEntityRef) {
745
+ if (userEntityRef) {
746
+ validateUserEntityRef(userEntityRef);
747
+ return `${MOCK_USER_TOKEN_PREFIX}${JSON.stringify({
748
+ sub: userEntityRef
749
+ })}`;
750
+ }
751
+ return MOCK_USER_TOKEN;
752
+ }
753
+ user2.token = token;
754
+ function header(userEntityRef) {
755
+ return `Bearer ${token(userEntityRef)}`;
756
+ }
757
+ user2.header = header;
758
+ function invalidToken() {
759
+ return MOCK_INVALID_USER_TOKEN;
760
+ }
761
+ user2.invalidToken = invalidToken;
762
+ function invalidHeader() {
763
+ return `Bearer ${invalidToken()}`;
764
+ }
765
+ user2.invalidHeader = invalidHeader;
766
+ })(user = mockCredentials2.user || (mockCredentials2.user = {}));
767
+ function limitedUser(userEntityRef = DEFAULT_MOCK_USER_ENTITY_REF) {
768
+ return user(userEntityRef);
769
+ }
770
+ mockCredentials2.limitedUser = limitedUser;
771
+ ((limitedUser2) => {
772
+ function token(userEntityRef = DEFAULT_MOCK_USER_ENTITY_REF) {
773
+ validateUserEntityRef(userEntityRef);
774
+ return `${MOCK_USER_LIMITED_TOKEN_PREFIX}${JSON.stringify({
775
+ sub: userEntityRef
776
+ })}`;
777
+ }
778
+ limitedUser2.token = token;
779
+ function cookie(userEntityRef) {
780
+ return `${MOCK_AUTH_COOKIE}=${token(userEntityRef)}`;
781
+ }
782
+ limitedUser2.cookie = cookie;
783
+ function invalidToken() {
784
+ return MOCK_INVALID_USER_LIMITED_TOKEN;
785
+ }
786
+ limitedUser2.invalidToken = invalidToken;
787
+ function invalidCookie() {
788
+ return `${MOCK_AUTH_COOKIE}=${invalidToken()}`;
789
+ }
790
+ limitedUser2.invalidCookie = invalidCookie;
791
+ })(limitedUser = mockCredentials2.limitedUser || (mockCredentials2.limitedUser = {}));
792
+ function service(subject = DEFAULT_MOCK_SERVICE_SUBJECT) {
793
+ return {
794
+ $$type: "@backstage/BackstageCredentials",
795
+ principal: { type: "service", subject }
796
+ };
797
+ }
798
+ mockCredentials2.service = service;
799
+ ((service2) => {
800
+ function token(options) {
801
+ if (options) {
802
+ const { targetPluginId, onBehalfOf } = options;
803
+ const oboPrincipal = onBehalfOf == null ? void 0 : onBehalfOf.principal;
804
+ const obo = oboPrincipal.type === "user" ? oboPrincipal.userEntityRef : void 0;
805
+ const subject = oboPrincipal.type === "service" ? oboPrincipal.subject : void 0;
806
+ return `${MOCK_SERVICE_TOKEN_PREFIX}${JSON.stringify({
807
+ sub: subject,
808
+ obo,
809
+ target: targetPluginId
810
+ })}`;
811
+ }
812
+ return MOCK_SERVICE_TOKEN;
813
+ }
814
+ service2.token = token;
815
+ function header(options) {
816
+ return `Bearer ${token(options)}`;
817
+ }
818
+ service2.header = header;
819
+ function invalidToken() {
820
+ return MOCK_INVALID_SERVICE_TOKEN;
821
+ }
822
+ service2.invalidToken = invalidToken;
823
+ function invalidHeader() {
824
+ return `Bearer ${invalidToken()}`;
825
+ }
826
+ service2.invalidHeader = invalidHeader;
827
+ })(service = mockCredentials2.service || (mockCredentials2.service = {}));
828
+ })(exports.mockCredentials || (exports.mockCredentials = {}));
829
+
830
+ var __defProp$1 = Object.defineProperty;
831
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
832
+ var __publicField$1 = (obj, key, value) => {
833
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
834
+ return value;
835
+ };
836
+ class MockAuthService {
837
+ constructor(options) {
838
+ __publicField$1(this, "pluginId");
839
+ __publicField$1(this, "disableDefaultAuthPolicy");
840
+ this.pluginId = options.pluginId;
841
+ this.disableDefaultAuthPolicy = options.disableDefaultAuthPolicy;
842
+ }
843
+ async authenticate(token, options) {
844
+ switch (token) {
845
+ case MOCK_USER_TOKEN:
846
+ return exports.mockCredentials.user();
847
+ case MOCK_SERVICE_TOKEN:
848
+ return exports.mockCredentials.service();
849
+ case MOCK_INVALID_USER_TOKEN:
850
+ throw new errors.AuthenticationError("User token is invalid");
851
+ case MOCK_INVALID_USER_LIMITED_TOKEN:
852
+ throw new errors.AuthenticationError("Limited user token is invalid");
853
+ case MOCK_INVALID_SERVICE_TOKEN:
854
+ throw new errors.AuthenticationError("Service token is invalid");
855
+ case "":
856
+ throw new errors.AuthenticationError("Token is empty");
857
+ }
858
+ if (token.startsWith(MOCK_USER_TOKEN_PREFIX)) {
859
+ const { sub: userEntityRef } = JSON.parse(
860
+ token.slice(MOCK_USER_TOKEN_PREFIX.length)
861
+ );
862
+ return exports.mockCredentials.user(userEntityRef);
863
+ }
864
+ if (token.startsWith(MOCK_USER_LIMITED_TOKEN_PREFIX)) {
865
+ if (!(options == null ? void 0 : options.allowLimitedAccess)) {
866
+ throw new errors.AuthenticationError("Limited user token is not allowed");
867
+ }
868
+ const { sub: userEntityRef } = JSON.parse(
869
+ token.slice(MOCK_USER_LIMITED_TOKEN_PREFIX.length)
870
+ );
871
+ return exports.mockCredentials.user(userEntityRef);
872
+ }
873
+ if (token.startsWith(MOCK_SERVICE_TOKEN_PREFIX)) {
874
+ const { sub, target, obo } = JSON.parse(
875
+ token.slice(MOCK_SERVICE_TOKEN_PREFIX.length)
876
+ );
877
+ if (target && target !== this.pluginId) {
878
+ throw new errors.AuthenticationError(
879
+ `Invalid mock token target plugin ID, got '${target}' but expected '${this.pluginId}'`
880
+ );
881
+ }
882
+ if (obo) {
883
+ return exports.mockCredentials.user(obo);
884
+ }
885
+ return exports.mockCredentials.service(sub);
886
+ }
887
+ throw new errors.AuthenticationError(`Unknown mock token '${token}'`);
888
+ }
889
+ async getNoneCredentials() {
890
+ return exports.mockCredentials.none();
891
+ }
892
+ async getOwnServiceCredentials() {
893
+ return exports.mockCredentials.service(`plugin:${this.pluginId}`);
894
+ }
895
+ isPrincipal(credentials, type) {
896
+ const principal = credentials.principal;
897
+ if (type === "unknown") {
898
+ return true;
899
+ }
900
+ if (principal.type !== type) {
901
+ return false;
902
+ }
903
+ return true;
904
+ }
905
+ async getPluginRequestToken(options) {
906
+ const principal = options.onBehalfOf.principal;
907
+ if (principal.type === "none" && this.disableDefaultAuthPolicy) {
908
+ return { token: "" };
909
+ }
910
+ if (principal.type !== "user" && principal.type !== "service") {
911
+ throw new errors.AuthenticationError(
912
+ `Refused to issue service token for credential type '${principal.type}'`
913
+ );
914
+ }
915
+ return {
916
+ token: exports.mockCredentials.service.token({
917
+ onBehalfOf: options.onBehalfOf,
918
+ targetPluginId: options.targetPluginId
919
+ })
920
+ };
921
+ }
922
+ async getLimitedUserToken(credentials) {
923
+ if (credentials.principal.type !== "user") {
924
+ throw new errors.AuthenticationError(
925
+ `Refused to issue limited user token for credential type '${credentials.principal.type}'`
926
+ );
927
+ }
928
+ return {
929
+ token: exports.mockCredentials.limitedUser.token(
930
+ credentials.principal.userEntityRef
931
+ ),
932
+ expiresAt: new Date(Date.now() + 36e5)
933
+ };
934
+ }
935
+ }
936
+
937
+ var __accessCheck$3 = (obj, member, msg) => {
938
+ if (!member.has(obj))
939
+ throw TypeError("Cannot " + msg);
940
+ };
941
+ var __privateGet$3 = (obj, member, getter) => {
942
+ __accessCheck$3(obj, member, "read from private field");
943
+ return getter ? getter.call(obj) : member.get(obj);
944
+ };
945
+ var __privateAdd$3 = (obj, member, value) => {
946
+ if (member.has(obj))
947
+ throw TypeError("Cannot add the same private member more than once");
948
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
949
+ };
950
+ var __privateSet$3 = (obj, member, value, setter) => {
951
+ __accessCheck$3(obj, member, "write to private field");
952
+ setter ? setter.call(obj, value) : member.set(obj, value);
953
+ return value;
954
+ };
955
+ var __privateMethod$2 = (obj, member, method) => {
956
+ __accessCheck$3(obj, member, "access private method");
957
+ return method;
958
+ };
959
+ var _auth, _defaultCredentials, _getCredentials, getCredentials_fn;
960
+ class MockHttpAuthService {
961
+ constructor(pluginId, defaultCredentials) {
962
+ __privateAdd$3(this, _getCredentials);
963
+ __privateAdd$3(this, _auth, void 0);
964
+ __privateAdd$3(this, _defaultCredentials, void 0);
965
+ __privateSet$3(this, _auth, new MockAuthService({
966
+ pluginId,
967
+ disableDefaultAuthPolicy: false
968
+ }));
969
+ __privateSet$3(this, _defaultCredentials, defaultCredentials);
970
+ }
971
+ async credentials(req, options) {
972
+ var _a;
973
+ const credentials = await __privateMethod$2(this, _getCredentials, getCredentials_fn).call(this, req, (_a = options == null ? void 0 : options.allowLimitedAccess) != null ? _a : false);
974
+ const allowedPrincipalTypes = options == null ? void 0 : options.allow;
975
+ if (!allowedPrincipalTypes) {
976
+ return credentials;
977
+ }
978
+ if (__privateGet$3(this, _auth).isPrincipal(credentials, "none")) {
979
+ if (allowedPrincipalTypes.includes("none")) {
980
+ return credentials;
981
+ }
982
+ throw new errors.AuthenticationError("Missing credentials");
983
+ } else if (__privateGet$3(this, _auth).isPrincipal(credentials, "user")) {
984
+ if (allowedPrincipalTypes.includes("user")) {
985
+ return credentials;
986
+ }
987
+ throw new errors.NotAllowedError(
988
+ `This endpoint does not allow 'user' credentials`
989
+ );
990
+ } else if (__privateGet$3(this, _auth).isPrincipal(credentials, "service")) {
991
+ if (allowedPrincipalTypes.includes("service")) {
992
+ return credentials;
993
+ }
994
+ throw new errors.NotAllowedError(
995
+ `This endpoint does not allow 'service' credentials`
996
+ );
997
+ }
998
+ throw new errors.NotAllowedError(
999
+ "Unknown principal type, this should never happen"
1000
+ );
1001
+ }
1002
+ async issueUserCookie(res, options) {
1003
+ var _a;
1004
+ const credentials = (_a = options == null ? void 0 : options.credentials) != null ? _a : await this.credentials(res.req, { allow: ["user"] });
1005
+ res.setHeader(
1006
+ "Set-Cookie",
1007
+ exports.mockCredentials.limitedUser.cookie(credentials.principal.userEntityRef)
1008
+ );
1009
+ return { expiresAt: new Date(Date.now() + 36e5) };
1010
+ }
1011
+ }
1012
+ _auth = new WeakMap();
1013
+ _defaultCredentials = new WeakMap();
1014
+ _getCredentials = new WeakSet();
1015
+ getCredentials_fn = async function(req, allowLimitedAccess) {
1016
+ var _a;
1017
+ const header = req.headers.authorization;
1018
+ const token = typeof header === "string" ? (_a = header.match(/^Bearer[ ]+(\S+)$/i)) == null ? void 0 : _a[1] : void 0;
1019
+ if (token) {
1020
+ if (token === MOCK_NONE_TOKEN) {
1021
+ return __privateGet$3(this, _auth).getNoneCredentials();
1022
+ }
1023
+ return await __privateGet$3(this, _auth).authenticate(token, {
1024
+ allowLimitedAccess
1025
+ });
1026
+ }
1027
+ if (allowLimitedAccess) {
1028
+ const cookieHeader = req.headers.cookie;
1029
+ if (cookieHeader) {
1030
+ const cookies = cookie.parse(cookieHeader);
1031
+ const cookie$1 = cookies[MOCK_AUTH_COOKIE];
1032
+ if (cookie$1) {
1033
+ return await __privateGet$3(this, _auth).authenticate(cookie$1, {
1034
+ allowLimitedAccess: true
1035
+ });
1036
+ }
1037
+ }
1038
+ }
1039
+ return __privateGet$3(this, _defaultCredentials);
1040
+ };
1041
+
1042
+ var __defProp = Object.defineProperty;
1043
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1044
+ var __publicField = (obj, key, value) => {
1045
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1046
+ return value;
1047
+ };
1048
+ class MockUserInfoService {
1049
+ constructor(customInfo) {
1050
+ __publicField(this, "customInfo");
1051
+ this.customInfo = customInfo != null ? customInfo : {};
1052
+ }
1053
+ async getUserInfo(credentials) {
1054
+ const principal = credentials.principal;
1055
+ if (principal.type !== "user") {
1056
+ throw new errors.InputError(
1057
+ `User info not available for principal type '${principal.type}'`
1058
+ );
1059
+ }
1060
+ return {
1061
+ userEntityRef: principal.userEntityRef,
1062
+ ownershipEntityRefs: [principal.userEntityRef],
1063
+ ...this.customInfo
1064
+ };
1065
+ }
1066
+ }
1067
+
700
1068
  function simpleFactory(ref, factory) {
701
1069
  return backendPluginApi.createServiceFactory((options) => ({
702
1070
  service: ref,
@@ -783,6 +1151,104 @@ exports.mockServices = void 0;
783
1151
  getIdentity: jest.fn()
784
1152
  }));
785
1153
  })(identity = mockServices2.identity || (mockServices2.identity = {}));
1154
+ function auth(options) {
1155
+ var _a;
1156
+ return new MockAuthService({
1157
+ pluginId: (_a = options == null ? void 0 : options.pluginId) != null ? _a : "test",
1158
+ disableDefaultAuthPolicy: Boolean(options == null ? void 0 : options.disableDefaultAuthPolicy)
1159
+ });
1160
+ }
1161
+ mockServices2.auth = auth;
1162
+ ((auth2) => {
1163
+ auth2.factory = backendPluginApi.createServiceFactory({
1164
+ service: backendPluginApi.coreServices.auth,
1165
+ deps: {
1166
+ plugin: backendPluginApi.coreServices.pluginMetadata,
1167
+ config: backendPluginApi.coreServices.rootConfig
1168
+ },
1169
+ factory({ plugin, config }) {
1170
+ const disableDefaultAuthPolicy = Boolean(
1171
+ config.getOptionalBoolean(
1172
+ "backend.auth.dangerouslyDisableDefaultAuthPolicy"
1173
+ )
1174
+ );
1175
+ return new MockAuthService({
1176
+ pluginId: plugin.getId(),
1177
+ disableDefaultAuthPolicy
1178
+ });
1179
+ }
1180
+ });
1181
+ auth2.mock = simpleMock(backendPluginApi.coreServices.auth, () => ({
1182
+ authenticate: jest.fn(),
1183
+ getNoneCredentials: jest.fn(),
1184
+ getOwnServiceCredentials: jest.fn(),
1185
+ isPrincipal: jest.fn(),
1186
+ getPluginRequestToken: jest.fn(),
1187
+ getLimitedUserToken: jest.fn()
1188
+ }));
1189
+ })(auth = mockServices2.auth || (mockServices2.auth = {}));
1190
+ function discovery() {
1191
+ return backendAppApi.HostDiscovery.fromConfig(
1192
+ new config.ConfigReader({
1193
+ backend: {
1194
+ // Invalid port to make sure that requests are always mocked
1195
+ baseUrl: "http://localhost:0",
1196
+ listen: { port: 0 }
1197
+ }
1198
+ })
1199
+ );
1200
+ }
1201
+ mockServices2.discovery = discovery;
1202
+ ((discovery2) => {
1203
+ discovery2.factory = backendAppApi.discoveryServiceFactory;
1204
+ discovery2.mock = simpleMock(backendPluginApi.coreServices.discovery, () => ({
1205
+ getBaseUrl: jest.fn(),
1206
+ getExternalBaseUrl: jest.fn()
1207
+ }));
1208
+ })(discovery = mockServices2.discovery || (mockServices2.discovery = {}));
1209
+ function httpAuth(options) {
1210
+ var _a, _b;
1211
+ return new MockHttpAuthService(
1212
+ (_a = options == null ? void 0 : options.pluginId) != null ? _a : "test",
1213
+ (_b = options == null ? void 0 : options.defaultCredentials) != null ? _b : exports.mockCredentials.user()
1214
+ );
1215
+ }
1216
+ mockServices2.httpAuth = httpAuth;
1217
+ ((httpAuth2) => {
1218
+ httpAuth2.factory = backendPluginApi.createServiceFactory(
1219
+ (options) => ({
1220
+ service: backendPluginApi.coreServices.httpAuth,
1221
+ deps: { plugin: backendPluginApi.coreServices.pluginMetadata },
1222
+ factory: ({ plugin }) => {
1223
+ var _a;
1224
+ return new MockHttpAuthService(
1225
+ plugin.getId(),
1226
+ (_a = options == null ? void 0 : options.defaultCredentials) != null ? _a : exports.mockCredentials.user()
1227
+ );
1228
+ }
1229
+ })
1230
+ );
1231
+ httpAuth2.mock = simpleMock(backendPluginApi.coreServices.httpAuth, () => ({
1232
+ credentials: jest.fn(),
1233
+ issueUserCookie: jest.fn()
1234
+ }));
1235
+ })(httpAuth = mockServices2.httpAuth || (mockServices2.httpAuth = {}));
1236
+ function userInfo(customInfo) {
1237
+ return new MockUserInfoService(customInfo);
1238
+ }
1239
+ mockServices2.userInfo = userInfo;
1240
+ ((userInfo2) => {
1241
+ userInfo2.factory = backendPluginApi.createServiceFactory({
1242
+ service: backendPluginApi.coreServices.userInfo,
1243
+ deps: {},
1244
+ factory() {
1245
+ return new MockUserInfoService();
1246
+ }
1247
+ });
1248
+ userInfo2.mock = simpleMock(backendPluginApi.coreServices.userInfo, () => ({
1249
+ getUserInfo: jest.fn()
1250
+ }));
1251
+ })(userInfo = mockServices2.userInfo || (mockServices2.userInfo = {}));
786
1252
  ((cache2) => {
787
1253
  cache2.factory = backendAppApi.cacheServiceFactory;
788
1254
  cache2.mock = simpleMock(backendPluginApi.coreServices.cache, () => ({
@@ -801,7 +1267,8 @@ exports.mockServices = void 0;
801
1267
  ((httpRouter2) => {
802
1268
  httpRouter2.factory = backendAppApi.httpRouterServiceFactory;
803
1269
  httpRouter2.mock = simpleMock(backendPluginApi.coreServices.httpRouter, () => ({
804
- use: jest.fn()
1270
+ use: jest.fn(),
1271
+ addAuthPolicy: jest.fn()
805
1272
  }));
806
1273
  })(mockServices2.httpRouter || (mockServices2.httpRouter = {}));
807
1274
  ((rootHttpRouter2) => {
@@ -861,9 +1328,11 @@ exports.mockServices = void 0;
861
1328
  })(exports.mockServices || (exports.mockServices = {}));
862
1329
 
863
1330
  const defaultServiceFactories = [
1331
+ exports.mockServices.auth.factory(),
864
1332
  exports.mockServices.cache.factory(),
865
1333
  exports.mockServices.rootConfig.factory(),
866
1334
  exports.mockServices.database.factory(),
1335
+ exports.mockServices.httpAuth.factory(),
867
1336
  exports.mockServices.httpRouter.factory(),
868
1337
  exports.mockServices.identity.factory(),
869
1338
  exports.mockServices.lifecycle.factory(),
@@ -873,6 +1342,7 @@ const defaultServiceFactories = [
873
1342
  exports.mockServices.rootLogger.factory(),
874
1343
  exports.mockServices.scheduler.factory(),
875
1344
  exports.mockServices.tokenManager.factory(),
1345
+ exports.mockServices.userInfo.factory(),
876
1346
  exports.mockServices.urlReader.factory()
877
1347
  ];
878
1348
  function createExtensionPointTestModules(features, extensionPointTuples) {