@backstage-community/plugin-rbac-backend 5.2.3

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.
Files changed (70) hide show
  1. package/CHANGELOG.md +671 -0
  2. package/README.md +220 -0
  3. package/config.d.ts +68 -0
  4. package/dist/admin-permissions/admin-creation.cjs.js +117 -0
  5. package/dist/admin-permissions/admin-creation.cjs.js.map +1 -0
  6. package/dist/audit-log/audit-logger.cjs.js +108 -0
  7. package/dist/audit-log/audit-logger.cjs.js.map +1 -0
  8. package/dist/audit-log/rest-errors-interceptor.cjs.js +100 -0
  9. package/dist/audit-log/rest-errors-interceptor.cjs.js.map +1 -0
  10. package/dist/conditional-aliases/alias-resolver.cjs.js +76 -0
  11. package/dist/conditional-aliases/alias-resolver.cjs.js.map +1 -0
  12. package/dist/database/casbin-adapter-factory.cjs.js +87 -0
  13. package/dist/database/casbin-adapter-factory.cjs.js.map +1 -0
  14. package/dist/database/conditional-storage.cjs.js +172 -0
  15. package/dist/database/conditional-storage.cjs.js.map +1 -0
  16. package/dist/database/migration.cjs.js +21 -0
  17. package/dist/database/migration.cjs.js.map +1 -0
  18. package/dist/database/role-metadata.cjs.js +89 -0
  19. package/dist/database/role-metadata.cjs.js.map +1 -0
  20. package/dist/file-permissions/csv-file-watcher.cjs.js +407 -0
  21. package/dist/file-permissions/csv-file-watcher.cjs.js.map +1 -0
  22. package/dist/file-permissions/file-watcher.cjs.js +46 -0
  23. package/dist/file-permissions/file-watcher.cjs.js.map +1 -0
  24. package/dist/file-permissions/yaml-conditional-file-watcher.cjs.js +208 -0
  25. package/dist/file-permissions/yaml-conditional-file-watcher.cjs.js.map +1 -0
  26. package/dist/helper.cjs.js +171 -0
  27. package/dist/helper.cjs.js.map +1 -0
  28. package/dist/index.cjs.js +14 -0
  29. package/dist/index.cjs.js.map +1 -0
  30. package/dist/index.d.ts +45 -0
  31. package/dist/plugin.cjs.js +79 -0
  32. package/dist/plugin.cjs.js.map +1 -0
  33. package/dist/policies/allow-all-policy.cjs.js +12 -0
  34. package/dist/policies/allow-all-policy.cjs.js.map +1 -0
  35. package/dist/policies/permission-policy.cjs.js +243 -0
  36. package/dist/policies/permission-policy.cjs.js.map +1 -0
  37. package/dist/providers/connect-providers.cjs.js +211 -0
  38. package/dist/providers/connect-providers.cjs.js.map +1 -0
  39. package/dist/role-manager/ancestor-search-memo.cjs.js +159 -0
  40. package/dist/role-manager/ancestor-search-memo.cjs.js.map +1 -0
  41. package/dist/role-manager/member-list.cjs.js +101 -0
  42. package/dist/role-manager/member-list.cjs.js.map +1 -0
  43. package/dist/role-manager/role-manager.cjs.js +281 -0
  44. package/dist/role-manager/role-manager.cjs.js.map +1 -0
  45. package/dist/service/enforcer-delegate.cjs.js +353 -0
  46. package/dist/service/enforcer-delegate.cjs.js.map +1 -0
  47. package/dist/service/permission-model.cjs.js +21 -0
  48. package/dist/service/permission-model.cjs.js.map +1 -0
  49. package/dist/service/plugin-endpoints.cjs.js +121 -0
  50. package/dist/service/plugin-endpoints.cjs.js.map +1 -0
  51. package/dist/service/policies-rest-api.cjs.js +949 -0
  52. package/dist/service/policies-rest-api.cjs.js.map +1 -0
  53. package/dist/service/policy-builder.cjs.js +134 -0
  54. package/dist/service/policy-builder.cjs.js.map +1 -0
  55. package/dist/service/router.cjs.js +24 -0
  56. package/dist/service/router.cjs.js.map +1 -0
  57. package/dist/validation/condition-validation.cjs.js +107 -0
  58. package/dist/validation/condition-validation.cjs.js.map +1 -0
  59. package/dist/validation/policies-validation.cjs.js +194 -0
  60. package/dist/validation/policies-validation.cjs.js.map +1 -0
  61. package/migrations/20231015161232_migrations.js +41 -0
  62. package/migrations/20231212224526_migrations.js +84 -0
  63. package/migrations/20231221113214_migrations.js +60 -0
  64. package/migrations/20240201144429_migrations.js +37 -0
  65. package/migrations/20240215154456_migrations.js +143 -0
  66. package/migrations/20240308134410_migrations.js +31 -0
  67. package/migrations/20240308134941_migrations.js +43 -0
  68. package/migrations/20240404111242_migrations.js +53 -0
  69. package/migrations/20240611092136_migrations.js +29 -0
  70. package/package.json +98 -0
@@ -0,0 +1,208 @@
1
+ 'use strict';
2
+
3
+ var yaml = require('js-yaml');
4
+ var lodash = require('lodash');
5
+ var fs = require('fs');
6
+ var auditLogger = require('../audit-log/audit-logger.cjs.js');
7
+ var helper = require('../helper.cjs.js');
8
+ var conditionValidation = require('../validation/condition-validation.cjs.js');
9
+ var fileWatcher = require('./file-watcher.cjs.js');
10
+
11
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
12
+
13
+ var yaml__default = /*#__PURE__*/_interopDefaultCompat(yaml);
14
+ var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
15
+
16
+ class YamlConditinalPoliciesFileWatcher extends fileWatcher.AbstractFileWatcher {
17
+ constructor(filePath, allowReload, logger, conditionalStorage, auditLogger, auth, pluginMetadataCollector, roleMetadataStorage, roleEventEmitter) {
18
+ super(filePath, allowReload, logger);
19
+ this.conditionalStorage = conditionalStorage;
20
+ this.auditLogger = auditLogger;
21
+ this.auth = auth;
22
+ this.pluginMetadataCollector = pluginMetadataCollector;
23
+ this.roleMetadataStorage = roleMetadataStorage;
24
+ this.roleEventEmitter = roleEventEmitter;
25
+ this.conditionsDiff = {
26
+ addedConditions: [],
27
+ removedConditions: []
28
+ };
29
+ }
30
+ conditionsDiff;
31
+ async initialize() {
32
+ if (!this.filePath) {
33
+ return;
34
+ }
35
+ const fileExists = fs__default.default.existsSync(this.filePath);
36
+ if (!fileExists) {
37
+ const err = new Error(`File '${this.filePath}' was not found`);
38
+ this.handleError(
39
+ err.message,
40
+ err,
41
+ auditLogger.ConditionEvents.CONDITIONAL_POLICIES_FILE_NOT_FOUND
42
+ );
43
+ return;
44
+ }
45
+ this.roleEventEmitter.on("roleAdded", this.onChange.bind(this));
46
+ await this.onChange();
47
+ if (this.allowReload) {
48
+ this.watchFile();
49
+ }
50
+ }
51
+ async onChange() {
52
+ try {
53
+ const newConds = this.parse().filter((c) => c);
54
+ const addedConds = [];
55
+ const removedConds = [];
56
+ const csvFileRoles = await this.roleMetadataStorage.filterRoleMetadata(
57
+ "csv-file"
58
+ );
59
+ const existedFileConds = (await this.conditionalStorage.filterConditions(
60
+ csvFileRoles.map((role) => role.roleEntityRef)
61
+ )).map((condition) => {
62
+ return {
63
+ ...condition,
64
+ permissionMapping: condition.permissionMapping.map((pm) => pm.action)
65
+ };
66
+ });
67
+ for (const condition of newConds) {
68
+ const roleMetadata = csvFileRoles.find(
69
+ (role) => condition.roleEntityRef === role.roleEntityRef
70
+ );
71
+ if (!roleMetadata) {
72
+ this.logger.warn(
73
+ `skip to add condition for role '${condition.roleEntityRef}'. The role either does not exist or was not created from a CSV file.`
74
+ );
75
+ continue;
76
+ }
77
+ if (roleMetadata.source !== "csv-file") {
78
+ this.logger.warn(
79
+ `skip to add condition for role '${condition.roleEntityRef}'. Role is not from csv-file`
80
+ );
81
+ continue;
82
+ }
83
+ const existingCondition = existedFileConds.find(
84
+ (c) => helper.deepSortEqual(lodash.omit(c, ["id"]), lodash.omit(condition, ["id"]))
85
+ );
86
+ if (!existingCondition) {
87
+ addedConds.push(condition);
88
+ }
89
+ }
90
+ for (const condition of existedFileConds) {
91
+ if (!newConds.find(
92
+ (c) => helper.deepSortEqual(lodash.omit(c, ["id"]), lodash.omit(condition, ["id"]))
93
+ )) {
94
+ removedConds.push(condition);
95
+ }
96
+ }
97
+ this.conditionsDiff = {
98
+ addedConditions: addedConds,
99
+ removedConditions: removedConds
100
+ };
101
+ await this.handleFileChanges();
102
+ } catch (error) {
103
+ await this.handleError(
104
+ `Error handling changes from conditional policies file ${this.filePath}`,
105
+ error,
106
+ auditLogger.ConditionEvents.CHANGE_CONDITIONAL_POLICIES_FILE_ERROR
107
+ );
108
+ }
109
+ }
110
+ /**
111
+ * Reads the current contents of the file and parses it.
112
+ * @returns parsed data.
113
+ */
114
+ parse() {
115
+ const fileContents = this.getCurrentContents();
116
+ const data = yaml__default.default.loadAll(
117
+ fileContents
118
+ );
119
+ for (const condition of data) {
120
+ conditionValidation.validateRoleCondition(condition);
121
+ }
122
+ return data;
123
+ }
124
+ async handleFileChanges() {
125
+ await this.removeConditions();
126
+ await this.addConditions();
127
+ }
128
+ async addConditions() {
129
+ try {
130
+ for (const condition of this.conditionsDiff.addedConditions) {
131
+ const conditionToCreate = await helper.processConditionMapping(
132
+ condition,
133
+ this.pluginMetadataCollector,
134
+ this.auth
135
+ );
136
+ await this.conditionalStorage.createCondition(conditionToCreate);
137
+ await this.auditLogger.auditLog({
138
+ message: `Created conditional permission policy`,
139
+ eventName: auditLogger.ConditionEvents.CREATE_CONDITION,
140
+ metadata: { condition },
141
+ stage: auditLogger.HANDLE_RBAC_DATA_STAGE,
142
+ status: "succeeded"
143
+ });
144
+ }
145
+ } catch (error) {
146
+ await this.handleError(
147
+ "Failed to create condition",
148
+ error,
149
+ auditLogger.ConditionEvents.CREATE_CONDITION_ERROR
150
+ );
151
+ }
152
+ this.conditionsDiff.addedConditions = [];
153
+ }
154
+ async removeConditions() {
155
+ try {
156
+ for (const condition of this.conditionsDiff.removedConditions) {
157
+ const conditionToDelete = (await this.conditionalStorage.filterConditions(
158
+ condition.roleEntityRef,
159
+ condition.pluginId,
160
+ condition.resourceType,
161
+ condition.permissionMapping
162
+ ))[0];
163
+ await this.conditionalStorage.deleteCondition(conditionToDelete.id);
164
+ await this.auditLogger.auditLog({
165
+ message: `Deleted conditional permission policy`,
166
+ eventName: auditLogger.ConditionEvents.DELETE_CONDITION,
167
+ metadata: { condition },
168
+ stage: auditLogger.HANDLE_RBAC_DATA_STAGE,
169
+ status: "succeeded"
170
+ });
171
+ }
172
+ } catch (error) {
173
+ await this.handleError(
174
+ "Failed to delete condition by id",
175
+ error,
176
+ auditLogger.ConditionEvents.DELETE_CONDITION_ERROR
177
+ );
178
+ }
179
+ this.conditionsDiff.removedConditions = [];
180
+ }
181
+ async handleError(message, error, event) {
182
+ await this.auditLogger.auditLog({
183
+ message,
184
+ eventName: event,
185
+ stage: auditLogger.HANDLE_RBAC_DATA_STAGE,
186
+ status: "failed",
187
+ errors: [error]
188
+ });
189
+ }
190
+ async cleanUpConditionalPolicies() {
191
+ const csvFileRoles = await this.roleMetadataStorage.filterRoleMetadata(
192
+ "csv-file"
193
+ );
194
+ const existedFileConds = (await this.conditionalStorage.filterConditions(
195
+ csvFileRoles.map((role) => role.roleEntityRef)
196
+ )).map((condition) => {
197
+ return {
198
+ ...condition,
199
+ permissionMapping: condition.permissionMapping.map((pm) => pm.action)
200
+ };
201
+ });
202
+ this.conditionsDiff.removedConditions = existedFileConds;
203
+ await this.removeConditions();
204
+ }
205
+ }
206
+
207
+ exports.YamlConditinalPoliciesFileWatcher = YamlConditinalPoliciesFileWatcher;
208
+ //# sourceMappingURL=yaml-conditional-file-watcher.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yaml-conditional-file-watcher.cjs.js","sources":["../../src/file-permissions/yaml-conditional-file-watcher.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { AuthService, LoggerService } from '@backstage/backend-plugin-api';\n\nimport type { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\nimport yaml from 'js-yaml';\nimport { omit } from 'lodash';\n\nimport type {\n PermissionAction,\n RoleConditionalPolicyDecision,\n} from '@backstage-community/plugin-rbac-common';\n\nimport fs from 'fs';\n\nimport {\n ConditionAuditInfo,\n ConditionEvents,\n HANDLE_RBAC_DATA_STAGE,\n} from '../audit-log/audit-logger';\nimport { ConditionalStorage } from '../database/conditional-storage';\nimport { RoleMetadataStorage } from '../database/role-metadata';\nimport { deepSortEqual, processConditionMapping } from '../helper';\nimport { RoleEventEmitter, RoleEvents } from '../service/enforcer-delegate';\nimport { PluginPermissionMetadataCollector } from '../service/plugin-endpoints';\nimport { validateRoleCondition } from '../validation/condition-validation';\nimport { AbstractFileWatcher } from './file-watcher';\n\ntype ConditionalPoliciesDiff = {\n addedConditions: RoleConditionalPolicyDecision<PermissionAction>[];\n removedConditions: RoleConditionalPolicyDecision<PermissionAction>[];\n};\n\nexport class YamlConditinalPoliciesFileWatcher extends AbstractFileWatcher<\n RoleConditionalPolicyDecision<PermissionAction>[]\n> {\n private conditionsDiff: ConditionalPoliciesDiff;\n\n constructor(\n filePath: string | undefined,\n allowReload: boolean,\n logger: LoggerService,\n private readonly conditionalStorage: ConditionalStorage,\n private readonly auditLogger: AuditLogger,\n private readonly auth: AuthService,\n private readonly pluginMetadataCollector: PluginPermissionMetadataCollector,\n private readonly roleMetadataStorage: RoleMetadataStorage,\n private readonly roleEventEmitter: RoleEventEmitter<RoleEvents>,\n ) {\n super(filePath, allowReload, logger);\n\n this.conditionsDiff = {\n addedConditions: [],\n removedConditions: [],\n };\n }\n\n async initialize(): Promise<void> {\n if (!this.filePath) {\n return;\n }\n const fileExists = fs.existsSync(this.filePath);\n if (!fileExists) {\n const err = new Error(`File '${this.filePath}' was not found`);\n this.handleError(\n err.message,\n err,\n ConditionEvents.CONDITIONAL_POLICIES_FILE_NOT_FOUND,\n );\n return;\n }\n\n this.roleEventEmitter.on('roleAdded', this.onChange.bind(this));\n await this.onChange();\n\n if (this.allowReload) {\n this.watchFile();\n }\n }\n\n async onChange(): Promise<void> {\n try {\n const newConds = this.parse().filter(c => c);\n\n const addedConds: RoleConditionalPolicyDecision<PermissionAction>[] = [];\n const removedConds: RoleConditionalPolicyDecision<PermissionAction>[] =\n [];\n\n const csvFileRoles = await this.roleMetadataStorage.filterRoleMetadata(\n 'csv-file',\n );\n const existedFileConds = (\n await this.conditionalStorage.filterConditions(\n csvFileRoles.map(role => role.roleEntityRef),\n )\n ).map(condition => {\n return {\n ...condition,\n permissionMapping: condition.permissionMapping.map(pm => pm.action),\n };\n });\n\n // Find added conditions\n for (const condition of newConds) {\n const roleMetadata = csvFileRoles.find(\n role => condition.roleEntityRef === role.roleEntityRef,\n );\n if (!roleMetadata) {\n this.logger.warn(\n `skip to add condition for role '${condition.roleEntityRef}'. The role either does not exist or was not created from a CSV file.`,\n );\n continue;\n }\n if (roleMetadata.source !== 'csv-file') {\n this.logger.warn(\n `skip to add condition for role '${condition.roleEntityRef}'. Role is not from csv-file`,\n );\n continue;\n }\n\n const existingCondition = existedFileConds.find(c =>\n deepSortEqual(omit(c, ['id']), omit(condition, ['id'])),\n );\n\n if (!existingCondition) {\n addedConds.push(condition);\n }\n }\n\n // Find removed conditions\n for (const condition of existedFileConds) {\n if (\n !newConds.find(c =>\n deepSortEqual(omit(c, ['id']), omit(condition, ['id'])),\n )\n ) {\n removedConds.push(condition);\n }\n }\n\n this.conditionsDiff = {\n addedConditions: addedConds,\n removedConditions: removedConds,\n };\n\n await this.handleFileChanges();\n } catch (error) {\n await this.handleError(\n `Error handling changes from conditional policies file ${this.filePath}`,\n error,\n ConditionEvents.CHANGE_CONDITIONAL_POLICIES_FILE_ERROR,\n );\n }\n }\n\n /**\n * Reads the current contents of the file and parses it.\n * @returns parsed data.\n */\n parse(): RoleConditionalPolicyDecision<PermissionAction>[] {\n const fileContents = this.getCurrentContents();\n const data = yaml.loadAll(\n fileContents,\n ) as RoleConditionalPolicyDecision<PermissionAction>[];\n\n for (const condition of data) {\n validateRoleCondition(condition);\n }\n\n return data;\n }\n\n private async handleFileChanges(): Promise<void> {\n await this.removeConditions();\n await this.addConditions();\n }\n\n private async addConditions(): Promise<void> {\n try {\n for (const condition of this.conditionsDiff.addedConditions) {\n const conditionToCreate = await processConditionMapping(\n condition,\n this.pluginMetadataCollector,\n this.auth,\n );\n\n await this.conditionalStorage.createCondition(conditionToCreate);\n\n await this.auditLogger.auditLog<ConditionAuditInfo>({\n message: `Created conditional permission policy`,\n eventName: ConditionEvents.CREATE_CONDITION,\n metadata: { condition },\n stage: HANDLE_RBAC_DATA_STAGE,\n status: 'succeeded',\n });\n }\n } catch (error) {\n await this.handleError(\n 'Failed to create condition',\n error,\n ConditionEvents.CREATE_CONDITION_ERROR,\n );\n }\n this.conditionsDiff.addedConditions = [];\n }\n\n private async removeConditions(): Promise<void> {\n try {\n for (const condition of this.conditionsDiff.removedConditions) {\n const conditionToDelete = (\n await this.conditionalStorage.filterConditions(\n condition.roleEntityRef,\n condition.pluginId,\n condition.resourceType,\n condition.permissionMapping,\n )\n )[0];\n await this.conditionalStorage.deleteCondition(conditionToDelete.id!);\n\n await this.auditLogger.auditLog<ConditionAuditInfo>({\n message: `Deleted conditional permission policy`,\n eventName: ConditionEvents.DELETE_CONDITION,\n metadata: { condition },\n stage: HANDLE_RBAC_DATA_STAGE,\n status: 'succeeded',\n });\n }\n } catch (error) {\n await this.handleError(\n 'Failed to delete condition by id',\n error,\n ConditionEvents.DELETE_CONDITION_ERROR,\n );\n }\n\n this.conditionsDiff.removedConditions = [];\n }\n\n private async handleError(\n message: string,\n error: unknown,\n event: string,\n ): Promise<void> {\n await this.auditLogger.auditLog({\n message,\n eventName: event,\n stage: HANDLE_RBAC_DATA_STAGE,\n status: 'failed',\n errors: [error],\n });\n }\n\n async cleanUpConditionalPolicies(): Promise<void> {\n const csvFileRoles = await this.roleMetadataStorage.filterRoleMetadata(\n 'csv-file',\n );\n const existedFileConds = (\n await this.conditionalStorage.filterConditions(\n csvFileRoles.map(role => role.roleEntityRef),\n )\n ).map(condition => {\n return {\n ...condition,\n permissionMapping: condition.permissionMapping.map(pm => pm.action),\n };\n });\n this.conditionsDiff.removedConditions = existedFileConds;\n await this.removeConditions();\n }\n}\n"],"names":["AbstractFileWatcher","fs","ConditionEvents","deepSortEqual","omit","yaml","validateRoleCondition","processConditionMapping","HANDLE_RBAC_DATA_STAGE"],"mappings":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AAA;AAAA,MACR,MAAA,EAAQ,CAAC,KAAK,CAAA;AAAA,KACf,CAAA,CAAA;AAAA,GACH;AAAA,EAEA,MAAM,0BAA4C,GAAA;AAChD,IAAM,MAAA,YAAA,GAAe,MAAM,IAAA,CAAK,mBAAoB,CAAA,kBAAA;AAAA,MAClD,UAAA;AAAA,KACF,CAAA;AACA,IAAM,MAAA,gBAAA,GAAA,CACJ,MAAM,IAAA,CAAK,kBAAmB,CAAA,gBAAA;AAAA,MAC5B,YAAa,CAAA,GAAA,CAAI,CAAQ,IAAA,KAAA,IAAA,CAAK,aAAa,CAAA;AAAA,KAC7C,EACA,IAAI,CAAa,SAAA,KAAA;AACjB,MAAO,OAAA;AAAA,QACL,GAAG,SAAA;AAAA,QACH,mBAAmB,SAAU,CAAA,iBAAA,CAAkB,GAAI,CAAA,CAAA,EAAA,KAAM,GAAG,MAAM,CAAA;AAAA,OACpE,CAAA;AAAA,KACD,CAAA,CAAA;AACD,IAAA,IAAA,CAAK,eAAe,iBAAoB,GAAA,gBAAA,CAAA;AACxC,IAAA,MAAM,KAAK,gBAAiB,EAAA,CAAA;AAAA,GAC9B;AACF;;;;"}
@@ -0,0 +1,171 @@
1
+ 'use strict';
2
+
3
+ var lodash = require('lodash');
4
+ var auditLogger = require('./audit-log/audit-logger.cjs.js');
5
+
6
+ function policyToString(policy) {
7
+ return `[${policy.join(", ")}]`;
8
+ }
9
+ function typedPolicyToString(policy, type) {
10
+ return `${type}, ${policy.join(", ")}`;
11
+ }
12
+ function policiesToString(policies) {
13
+ const policiesString = policies.map((policy) => policyToString(policy)).join(",");
14
+ return `[${policiesString}]`;
15
+ }
16
+ function typedPoliciesToString(policies, type) {
17
+ const policiesString = policies.map((policy) => {
18
+ return policy.length !== 0 ? typedPolicyToString(policy, type) : "";
19
+ }).join("\n");
20
+ return `
21
+ ${policiesString}
22
+ `;
23
+ }
24
+ function metadataStringToPolicy(policy) {
25
+ return policy.replace("[", "").replace("]", "").split(", ");
26
+ }
27
+ async function removeTheDifference(originalGroup, addedGroup, source, roleEntityRef, enf, auditLogger$1, modifiedBy) {
28
+ originalGroup.sort((a, b) => a.localeCompare(b));
29
+ addedGroup.sort((a, b) => a.localeCompare(b));
30
+ const missing = lodash.difference(originalGroup, addedGroup);
31
+ const groupPolicies = [];
32
+ for (const missingRole of missing) {
33
+ groupPolicies.push([missingRole, roleEntityRef]);
34
+ }
35
+ if (groupPolicies.length === 0) {
36
+ return;
37
+ }
38
+ const roleMetadata = { source, modifiedBy, roleEntityRef };
39
+ await enf.removeGroupingPolicies(groupPolicies, roleMetadata, false);
40
+ const remainingMembers = await enf.getFilteredGroupingPolicy(
41
+ 1,
42
+ roleEntityRef
43
+ );
44
+ const message = remainingMembers.length > 0 ? "Updated role: deleted members" : "Deleted role";
45
+ const eventName = remainingMembers.length > 0 ? auditLogger.RoleEvents.UPDATE_ROLE : auditLogger.RoleEvents.DELETE_ROLE;
46
+ await auditLogger$1.auditLog({
47
+ actorId: auditLogger.RBAC_BACKEND,
48
+ message,
49
+ eventName,
50
+ metadata: {
51
+ ...roleMetadata,
52
+ members: groupPolicies.map((gp) => gp[0])
53
+ },
54
+ stage: auditLogger.HANDLE_RBAC_DATA_STAGE,
55
+ status: "succeeded"
56
+ });
57
+ }
58
+ function transformArrayToPolicy(policyArray) {
59
+ const [entityReference, permission, policy, effect] = policyArray;
60
+ return { entityReference, permission, policy, effect };
61
+ }
62
+ function deepSortedEqual(obj1, obj2, excludeFields) {
63
+ let copyObj1;
64
+ let copyObj2;
65
+ if (excludeFields) {
66
+ const excludeFieldsPredicate = (_value, key) => {
67
+ for (const field of excludeFields) {
68
+ if (key === field) {
69
+ return true;
70
+ }
71
+ }
72
+ return false;
73
+ };
74
+ copyObj1 = lodash.omitBy(obj1, excludeFieldsPredicate);
75
+ copyObj2 = lodash.omitBy(obj2, excludeFieldsPredicate);
76
+ }
77
+ const sortedObj1 = lodash.sortBy(lodash.toPairs(copyObj1 || obj1), ([key]) => key);
78
+ const sortedObj2 = lodash.sortBy(lodash.toPairs(copyObj2 || obj2), ([key]) => key);
79
+ return lodash.isEqual(sortedObj1, sortedObj2);
80
+ }
81
+ function isPermissionAction(action) {
82
+ return ["create", "read", "update", "delete", "use"].includes(
83
+ action
84
+ );
85
+ }
86
+ async function buildRoleSourceMap(policies, roleMetadata) {
87
+ return await policies.reduce(
88
+ async (acc, policy) => {
89
+ const roleEntityRef = policy[0];
90
+ const acummulator = await acc;
91
+ if (!acummulator.has(roleEntityRef)) {
92
+ const metadata = await roleMetadata.findRoleMetadata(roleEntityRef);
93
+ acummulator.set(roleEntityRef, metadata?.source);
94
+ }
95
+ return acummulator;
96
+ },
97
+ Promise.resolve(/* @__PURE__ */ new Map())
98
+ );
99
+ }
100
+ function mergeRoleMetadata(currentMetadata, newMetadata) {
101
+ const mergedMetaData = { ...currentMetadata };
102
+ mergedMetaData.lastModified = newMetadata.lastModified ?? (/* @__PURE__ */ new Date()).toUTCString();
103
+ mergedMetaData.modifiedBy = newMetadata.modifiedBy;
104
+ mergedMetaData.description = newMetadata.description ?? currentMetadata.description;
105
+ mergedMetaData.roleEntityRef = newMetadata.roleEntityRef;
106
+ mergedMetaData.source = newMetadata.source;
107
+ return mergedMetaData;
108
+ }
109
+ async function processConditionMapping(roleConditionPolicy, pluginPermMetaData, auth) {
110
+ const { token } = await auth.getPluginRequestToken({
111
+ onBehalfOf: await auth.getOwnServiceCredentials(),
112
+ targetPluginId: roleConditionPolicy.pluginId
113
+ });
114
+ const rule = await pluginPermMetaData.getMetadataByPluginId(
115
+ roleConditionPolicy.pluginId,
116
+ token
117
+ );
118
+ if (!rule?.permissions) {
119
+ throw new Error(
120
+ `Unable to get permission list for plugin ${roleConditionPolicy.pluginId}`
121
+ );
122
+ }
123
+ const permInfo = [];
124
+ for (const action of roleConditionPolicy.permissionMapping) {
125
+ const perm = rule.permissions.find(
126
+ (permission) => permission.type === "resource" && (action === permission.attributes.action || action === "use" && permission.attributes.action === void 0)
127
+ );
128
+ if (!perm) {
129
+ throw new Error(
130
+ `Unable to find permission to get permission name for resource type '${roleConditionPolicy.resourceType}' and action ${JSON.stringify(action)}`
131
+ );
132
+ }
133
+ permInfo.push({ name: perm.name, action });
134
+ }
135
+ return {
136
+ ...roleConditionPolicy,
137
+ permissionMapping: permInfo
138
+ };
139
+ }
140
+ function deepSort(value) {
141
+ if (lodash.isArray(value)) {
142
+ return lodash.sortBy(value.map(deepSort));
143
+ } else if (lodash.isPlainObject(value)) {
144
+ return lodash.fromPairs(
145
+ lodash.sortBy(
146
+ lodash.toPairs(value).map(([k, v]) => [k, deepSort(v)]),
147
+ 0
148
+ )
149
+ );
150
+ }
151
+ return value;
152
+ }
153
+ function deepSortEqual(obj1, obj2) {
154
+ return lodash.isEqual(deepSort(obj1), deepSort(obj2));
155
+ }
156
+
157
+ exports.buildRoleSourceMap = buildRoleSourceMap;
158
+ exports.deepSort = deepSort;
159
+ exports.deepSortEqual = deepSortEqual;
160
+ exports.deepSortedEqual = deepSortedEqual;
161
+ exports.isPermissionAction = isPermissionAction;
162
+ exports.mergeRoleMetadata = mergeRoleMetadata;
163
+ exports.metadataStringToPolicy = metadataStringToPolicy;
164
+ exports.policiesToString = policiesToString;
165
+ exports.policyToString = policyToString;
166
+ exports.processConditionMapping = processConditionMapping;
167
+ exports.removeTheDifference = removeTheDifference;
168
+ exports.transformArrayToPolicy = transformArrayToPolicy;
169
+ exports.typedPoliciesToString = typedPoliciesToString;
170
+ exports.typedPolicyToString = typedPolicyToString;
171
+ //# sourceMappingURL=helper.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helper.cjs.js","sources":["../src/helper.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport type { MetadataResponse } from '@backstage/plugin-permission-node';\n\nimport { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\nimport {\n difference,\n fromPairs,\n isArray,\n isEqual,\n isPlainObject,\n omitBy,\n sortBy,\n toPairs,\n ValueKeyIteratee,\n} from 'lodash';\n\nimport {\n PermissionAction,\n PermissionInfo,\n RoleBasedPolicy,\n RoleConditionalPolicyDecision,\n Source,\n} from '@backstage-community/plugin-rbac-common';\n\nimport {\n HANDLE_RBAC_DATA_STAGE,\n RBAC_BACKEND,\n RoleAuditInfo,\n RoleEvents,\n} from './audit-log/audit-logger';\nimport { RoleMetadataDao, RoleMetadataStorage } from './database/role-metadata';\nimport { EnforcerDelegate } from './service/enforcer-delegate';\nimport { PluginPermissionMetadataCollector } from './service/plugin-endpoints';\n\nexport function policyToString(policy: string[]): string {\n return `[${policy.join(', ')}]`;\n}\n\nexport function typedPolicyToString(policy: string[], type: string): string {\n return `${type}, ${policy.join(', ')}`;\n}\n\nexport function policiesToString(policies: string[][]): string {\n const policiesString = policies\n .map(policy => policyToString(policy))\n .join(',');\n return `[${policiesString}]`;\n}\n\nexport function typedPoliciesToString(\n policies: string[][],\n type: string,\n): string {\n const policiesString = policies\n .map(policy => {\n return policy.length !== 0 ? typedPolicyToString(policy, type) : '';\n })\n .join('\\n');\n return `\n ${policiesString}\n `;\n}\n\nexport function metadataStringToPolicy(policy: string): string[] {\n return policy.replace('[', '').replace(']', '').split(', ');\n}\n\nexport async function removeTheDifference(\n originalGroup: string[],\n addedGroup: string[],\n source: Source,\n roleEntityRef: string,\n enf: EnforcerDelegate,\n auditLogger: AuditLogger,\n modifiedBy: string,\n): Promise<void> {\n originalGroup.sort((a, b) => a.localeCompare(b));\n addedGroup.sort((a, b) => a.localeCompare(b));\n const missing = difference(originalGroup, addedGroup);\n\n const groupPolicies: string[][] = [];\n for (const missingRole of missing) {\n groupPolicies.push([missingRole, roleEntityRef]);\n }\n\n if (groupPolicies.length === 0) {\n return;\n }\n\n const roleMetadata = { source, modifiedBy, roleEntityRef };\n await enf.removeGroupingPolicies(groupPolicies, roleMetadata, false);\n\n const remainingMembers = await enf.getFilteredGroupingPolicy(\n 1,\n roleEntityRef,\n );\n const message =\n remainingMembers.length > 0\n ? 'Updated role: deleted members'\n : 'Deleted role';\n const eventName =\n remainingMembers.length > 0\n ? RoleEvents.UPDATE_ROLE\n : RoleEvents.DELETE_ROLE;\n await auditLogger.auditLog<RoleAuditInfo>({\n actorId: RBAC_BACKEND,\n message,\n eventName,\n metadata: {\n ...roleMetadata,\n members: groupPolicies.map(gp => gp[0]),\n },\n stage: HANDLE_RBAC_DATA_STAGE,\n status: 'succeeded',\n });\n}\n\nexport function transformArrayToPolicy(policyArray: string[]): RoleBasedPolicy {\n const [entityReference, permission, policy, effect] = policyArray;\n return { entityReference, permission, policy, effect };\n}\n\nexport function deepSortedEqual(\n obj1: Record<string, any>,\n obj2: Record<string, any>,\n excludeFields?: string[],\n): boolean {\n let copyObj1;\n let copyObj2;\n if (excludeFields) {\n const excludeFieldsPredicate: ValueKeyIteratee<any> = (_value, key) => {\n for (const field of excludeFields) {\n if (key === field) {\n return true;\n }\n }\n return false;\n };\n copyObj1 = omitBy(obj1, excludeFieldsPredicate);\n copyObj2 = omitBy(obj2, excludeFieldsPredicate);\n }\n\n const sortedObj1 = sortBy(toPairs(copyObj1 || obj1), ([key]) => key);\n const sortedObj2 = sortBy(toPairs(copyObj2 || obj2), ([key]) => key);\n\n return isEqual(sortedObj1, sortedObj2);\n}\n\nexport function isPermissionAction(action: string): action is PermissionAction {\n return ['create', 'read', 'update', 'delete', 'use'].includes(\n action as PermissionAction,\n );\n}\n\nexport async function buildRoleSourceMap(\n policies: string[][],\n roleMetadata: RoleMetadataStorage,\n): Promise<Map<string, Source | undefined>> {\n return await policies.reduce(\n async (\n acc: Promise<Map<string, Source | undefined>>,\n policy: string[],\n ): Promise<Map<string, Source | undefined>> => {\n const roleEntityRef = policy[0];\n const acummulator = await acc;\n if (!acummulator.has(roleEntityRef)) {\n const metadata = await roleMetadata.findRoleMetadata(roleEntityRef);\n acummulator.set(roleEntityRef, metadata?.source);\n }\n return acummulator;\n },\n Promise.resolve(new Map<string, Source | undefined>()),\n );\n}\n\nexport function mergeRoleMetadata(\n currentMetadata: RoleMetadataDao,\n newMetadata: RoleMetadataDao,\n): RoleMetadataDao {\n const mergedMetaData: RoleMetadataDao = { ...currentMetadata };\n mergedMetaData.lastModified =\n newMetadata.lastModified ?? new Date().toUTCString();\n mergedMetaData.modifiedBy = newMetadata.modifiedBy;\n mergedMetaData.description =\n newMetadata.description ?? currentMetadata.description;\n mergedMetaData.roleEntityRef = newMetadata.roleEntityRef;\n mergedMetaData.source = newMetadata.source;\n return mergedMetaData;\n}\n\nexport async function processConditionMapping(\n roleConditionPolicy: RoleConditionalPolicyDecision<PermissionAction>,\n pluginPermMetaData: PluginPermissionMetadataCollector,\n auth: AuthService,\n): Promise<RoleConditionalPolicyDecision<PermissionInfo>> {\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId: roleConditionPolicy.pluginId,\n });\n\n const rule: MetadataResponse | undefined =\n await pluginPermMetaData.getMetadataByPluginId(\n roleConditionPolicy.pluginId,\n token,\n );\n if (!rule?.permissions) {\n throw new Error(\n `Unable to get permission list for plugin ${roleConditionPolicy.pluginId}`,\n );\n }\n\n const permInfo: PermissionInfo[] = [];\n for (const action of roleConditionPolicy.permissionMapping) {\n const perm = rule.permissions.find(\n permission =>\n permission.type === 'resource' &&\n (action === permission.attributes.action ||\n (action === 'use' && permission.attributes.action === undefined)),\n );\n if (!perm) {\n throw new Error(\n `Unable to find permission to get permission name for resource type '${\n roleConditionPolicy.resourceType\n }' and action ${JSON.stringify(action)}`,\n );\n }\n permInfo.push({ name: perm.name, action });\n }\n\n return {\n ...roleConditionPolicy,\n permissionMapping: permInfo,\n };\n}\n\nexport function deepSort(value: any): any {\n if (isArray(value)) {\n return sortBy(value.map(deepSort));\n } else if (isPlainObject(value)) {\n return fromPairs(\n sortBy(\n toPairs(value).map(([k, v]: [string, any]) => [k, deepSort(v)]),\n 0,\n ),\n );\n }\n return value;\n}\n\nexport function deepSortEqual(obj1: any, obj2: any): boolean {\n return isEqual(deepSort(obj1), deepSort(obj2));\n}\n"],"names":["auditLogger","difference","RoleEvents","RBAC_BACKEND","HANDLE_RBAC_DATA_STAGE","omitBy","sortBy","toPairs","isEqual","isArray","isPlainObject","fromPairs"],"mappings":";;;;;AAiDO,SAAS,eAAe,MAA0B,EAAA;AACvD,EAAA,OAAO,CAAI,CAAA,EAAA,MAAA,CAAO,IAAK,CAAA,IAAI,CAAC,CAAA,CAAA,CAAA,CAAA;AAC9B,CAAA;AAEgB,SAAA,mBAAA,CAAoB,QAAkB,IAAsB,EAAA;AAC1E,EAAA,OAAO,GAAG,IAAI,CAAA,EAAA,EAAK,MAAO,CAAA,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AACtC,CAAA;AAEO,SAAS,iBAAiB,QAA8B,EAAA;AAC7D,EAAM,MAAA,cAAA,GAAiB,SACpB,GAAI,CAAA,CAAA,MAAA,KAAU,eAAe,MAAM,CAAC,CACpC,CAAA,IAAA,CAAK,GAAG,CAAA,CAAA;AACX,EAAA,OAAO,IAAI,cAAc,CAAA,CAAA,CAAA,CAAA;AAC3B,CAAA;AAEgB,SAAA,qBAAA,CACd,UACA,IACQ,EAAA;AACR,EAAM,MAAA,cAAA,GAAiB,QACpB,CAAA,GAAA,CAAI,CAAU,MAAA,KAAA;AACb,IAAA,OAAO,OAAO,MAAW,KAAA,CAAA,GAAI,mBAAoB,CAAA,MAAA,EAAQ,IAAI,CAAI,GAAA,EAAA,CAAA;AAAA,GAClE,CACA,CAAA,IAAA,CAAK,IAAI,CAAA,CAAA;AACZ,EAAO,OA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AAAA,KAC5D,CAAA;AACA,IAAA,IAAI,CAAC,IAAM,EAAA;AACT,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,uEACE,mBAAoB,CAAA,YACtB,gBAAgB,IAAK,CAAA,SAAA,CAAU,MAAM,CAAC,CAAA,CAAA;AAAA,OACxC,CAAA;AAAA,KACF;AACA,IAAA,QAAA,CAAS,KAAK,EAAE,IAAA,EAAM,IAAK,CAAA,IAAA,EAAM,QAAQ,CAAA,CAAA;AAAA,GAC3C;AAEA,EAAO,OAAA;AAAA,IACL,GAAG,mBAAA;AAAA,IACH,iBAAmB,EAAA,QAAA;AAAA,GACrB,CAAA;AACF,CAAA;AAEO,SAAS,SAAS,KAAiB,EAAA;AACxC,EAAI,IAAAC,cAAA,CAAQ,KAAK,CAAG,EAAA;AAClB,IAAA,OAAOH,aAAO,CAAA,KAAA,CAAM,GAAI,CAAA,QAAQ,CAAC,CAAA,CAAA;AAAA,GACnC,MAAA,IAAWI,oBAAc,CAAA,KAAK,CAAG,EAAA;AAC/B,IAAO,OAAAC,gBAAA;AAAA,MACLL,aAAA;AAAA,QACEC,cAAQ,CAAA,KAAK,CAAE,CAAA,GAAA,CAAI,CAAC,CAAC,CAAA,EAAG,CAAC,CAAA,KAAqB,CAAC,CAAA,EAAG,QAAS,CAAA,CAAC,CAAC,CAAC,CAAA;AAAA,QAC9D,CAAA;AAAA,OACF;AAAA,KACF,CAAA;AAAA,GACF;AACA,EAAO,OAAA,KAAA,CAAA;AACT,CAAA;AAEgB,SAAA,aAAA,CAAc,MAAW,IAAoB,EAAA;AAC3D,EAAA,OAAOC,eAAQ,QAAS,CAAA,IAAI,CAAG,EAAA,QAAA,CAAS,IAAI,CAAC,CAAA,CAAA;AAC/C;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var router = require('./service/router.cjs.js');
6
+ var policyBuilder = require('./service/policy-builder.cjs.js');
7
+ var plugin = require('./plugin.cjs.js');
8
+
9
+
10
+
11
+ exports.createRouter = router.createRouter;
12
+ exports.PolicyBuilder = policyBuilder.PolicyBuilder;
13
+ exports.default = plugin.rbacPlugin;
14
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"}
@@ -0,0 +1,45 @@
1
+ import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
2
+ import { LoggerService, DiscoveryService, AuthService, HttpAuthService, UserInfoService, LifecycleService } from '@backstage/backend-plugin-api';
3
+ import { Config } from '@backstage/config';
4
+ import express, { Router } from 'express';
5
+ import { PermissionEvaluator } from '@backstage/plugin-permission-common';
6
+ import { PermissionPolicy } from '@backstage/plugin-permission-node';
7
+ import { PluginIdProvider, RBACProvider } from '@backstage-community/plugin-rbac-node';
8
+ export { PluginIdProvider } from '@backstage-community/plugin-rbac-node';
9
+
10
+ interface RouterOptions {
11
+ logger: LoggerService;
12
+ config: Config;
13
+ }
14
+ declare function createRouter(options: RouterOptions): Promise<express.Router>;
15
+
16
+ type EnvOptions = {
17
+ config: Config;
18
+ logger: LoggerService;
19
+ discovery: DiscoveryService;
20
+ permissions: PermissionEvaluator;
21
+ auth: AuthService;
22
+ httpAuth: HttpAuthService;
23
+ userInfo: UserInfoService;
24
+ lifecycle: LifecycleService;
25
+ };
26
+ type RBACRouterOptions = {
27
+ config: Config;
28
+ logger: LoggerService;
29
+ discovery: DiscoveryService;
30
+ policy: PermissionPolicy;
31
+ auth: AuthService;
32
+ httpAuth: HttpAuthService;
33
+ userInfo: UserInfoService;
34
+ };
35
+ declare class PolicyBuilder {
36
+ static build(env: EnvOptions, pluginIdProvider?: PluginIdProvider, rbacProviders?: Array<RBACProvider>): Promise<Router>;
37
+ }
38
+
39
+ /**
40
+ * RBAC plugin
41
+ *
42
+ */
43
+ declare const rbacPlugin: _backstage_backend_plugin_api.BackendFeature;
44
+
45
+ export { type EnvOptions, PolicyBuilder, type RBACRouterOptions, type RouterOptions, createRouter, rbacPlugin as default };
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ var backendPluginApi = require('@backstage/backend-plugin-api');
4
+ var pluginRbacBackend = require('@backstage-community/plugin-rbac-backend');
5
+ var pluginRbacNode = require('@backstage-community/plugin-rbac-node');
6
+
7
+ const rbacPlugin = backendPluginApi.createBackendPlugin({
8
+ pluginId: "permission",
9
+ register(env) {
10
+ const pluginIdProviderExtensionPointImpl = new class PluginIdProviderImpl {
11
+ pluginIdProviders = [];
12
+ addPluginIdProvider(pluginIdProvider) {
13
+ this.pluginIdProviders.push(pluginIdProvider);
14
+ }
15
+ }();
16
+ env.registerExtensionPoint(
17
+ pluginRbacNode.pluginIdProviderExtensionPoint,
18
+ pluginIdProviderExtensionPointImpl
19
+ );
20
+ const rbacProviders = new Array();
21
+ env.registerExtensionPoint(pluginRbacNode.rbacProviderExtensionPoint, {
22
+ addRBACProvider(...providers) {
23
+ rbacProviders.push(...providers.flat());
24
+ }
25
+ });
26
+ env.registerInit({
27
+ deps: {
28
+ http: backendPluginApi.coreServices.httpRouter,
29
+ config: backendPluginApi.coreServices.rootConfig,
30
+ logger: backendPluginApi.coreServices.logger,
31
+ discovery: backendPluginApi.coreServices.discovery,
32
+ permissions: backendPluginApi.coreServices.permissions,
33
+ auth: backendPluginApi.coreServices.auth,
34
+ httpAuth: backendPluginApi.coreServices.httpAuth,
35
+ userInfo: backendPluginApi.coreServices.userInfo,
36
+ lifecycle: backendPluginApi.coreServices.lifecycle
37
+ },
38
+ async init({
39
+ http,
40
+ config,
41
+ logger,
42
+ discovery,
43
+ permissions,
44
+ auth,
45
+ httpAuth,
46
+ userInfo,
47
+ lifecycle
48
+ }) {
49
+ http.use(
50
+ await pluginRbacBackend.PolicyBuilder.build(
51
+ {
52
+ config,
53
+ logger,
54
+ discovery,
55
+ permissions,
56
+ auth,
57
+ httpAuth,
58
+ userInfo,
59
+ lifecycle
60
+ },
61
+ {
62
+ getPluginIds: () => Array.from(
63
+ new Set(
64
+ pluginIdProviderExtensionPointImpl.pluginIdProviders.flatMap(
65
+ (p) => p.getPluginIds()
66
+ )
67
+ )
68
+ )
69
+ },
70
+ rbacProviders
71
+ )
72
+ );
73
+ }
74
+ });
75
+ }
76
+ });
77
+
78
+ exports.rbacPlugin = rbacPlugin;
79
+ //# sourceMappingURL=plugin.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.cjs.js","sources":["../src/plugin.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\n\nimport { PolicyBuilder } from '@backstage-community/plugin-rbac-backend';\nimport {\n PluginIdProvider,\n PluginIdProviderExtensionPoint,\n pluginIdProviderExtensionPoint,\n RBACProvider,\n rbacProviderExtensionPoint,\n} from '@backstage-community/plugin-rbac-node';\n\n/**\n * RBAC plugin\n *\n */\nexport const rbacPlugin = createBackendPlugin({\n pluginId: 'permission',\n register(env) {\n const pluginIdProviderExtensionPointImpl = new (class PluginIdProviderImpl\n implements PluginIdProviderExtensionPoint\n {\n pluginIdProviders: PluginIdProvider[] = [];\n\n addPluginIdProvider(pluginIdProvider: PluginIdProvider): void {\n this.pluginIdProviders.push(pluginIdProvider);\n }\n })();\n\n env.registerExtensionPoint(\n pluginIdProviderExtensionPoint,\n pluginIdProviderExtensionPointImpl,\n );\n\n const rbacProviders = new Array<RBACProvider>();\n\n env.registerExtensionPoint(rbacProviderExtensionPoint, {\n addRBACProvider(\n ...providers: Array<RBACProvider | Array<RBACProvider>>\n ): void {\n rbacProviders.push(...providers.flat());\n },\n });\n\n env.registerInit({\n deps: {\n http: coreServices.httpRouter,\n config: coreServices.rootConfig,\n logger: coreServices.logger,\n discovery: coreServices.discovery,\n permissions: coreServices.permissions,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n userInfo: coreServices.userInfo,\n lifecycle: coreServices.lifecycle,\n },\n async init({\n http,\n config,\n logger,\n discovery,\n permissions,\n auth,\n httpAuth,\n userInfo,\n lifecycle,\n }) {\n http.use(\n await PolicyBuilder.build(\n {\n config,\n logger,\n discovery,\n permissions,\n auth,\n httpAuth,\n userInfo,\n lifecycle,\n },\n {\n getPluginIds: () =>\n Array.from(\n new Set(\n pluginIdProviderExtensionPointImpl.pluginIdProviders.flatMap(\n p => p.getPluginIds(),\n ),\n ),\n ),\n },\n rbacProviders,\n ),\n );\n },\n });\n },\n});\n"],"names":["createBackendPlugin","pluginIdProviderExtensionPoint","rbacProviderExtensionPoint","coreServices","PolicyBuilder"],"mappings":";;;;;;AAiCO,MAAM,aAAaA,oCAAoB,CAAA;AAAA,EAC5C,QAAU,EAAA,YAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAM,MAAA,kCAAA,GAAqC,IAAK,MAAM,oBAEtD,CAAA;AAAA,MACE,oBAAwC,EAAC,CAAA;AAAA,MAEzC,oBAAoB,gBAA0C,EAAA;AAC5D,QAAK,IAAA,CAAA,iBAAA,CAAkB,KAAK,gBAAgB,CAAA,CAAA;AAAA,OAC9C;AAAA,KACC,EAAA,CAAA;AAEH,IAAI,GAAA,CAAA,sBAAA;AAAA,MACFC,6CAAA;AAAA,MACA,kCAAA;AAAA,KACF,CAAA;AAEA,IAAM,MAAA,aAAA,GAAgB,IAAI,KAAoB,EAAA,CAAA;AAE9C,IAAA,GAAA,CAAI,uBAAuBC,yCAA4B,EAAA;AAAA,MACrD,mBACK,SACG,EAAA;AACN,QAAA,aAA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AAA;AAAA,GACH;AACF,CAAC;;;;"}
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ var pluginPermissionCommon = require('@backstage/plugin-permission-common');
4
+
5
+ class AllowAllPolicy {
6
+ async handle(_request, _user) {
7
+ return { result: pluginPermissionCommon.AuthorizeResult.ALLOW };
8
+ }
9
+ }
10
+
11
+ exports.AllowAllPolicy = AllowAllPolicy;
12
+ //# sourceMappingURL=allow-all-policy.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allow-all-policy.cjs.js","sources":["../../src/policies/allow-all-policy.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AuthorizeResult,\n PolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport {\n PermissionPolicy,\n PolicyQuery,\n PolicyQueryUser,\n} from '@backstage/plugin-permission-node';\n\nexport class AllowAllPolicy implements PermissionPolicy {\n async handle(\n _request: PolicyQuery,\n _user?: PolicyQueryUser,\n ): Promise<PolicyDecision> {\n return { result: AuthorizeResult.ALLOW };\n }\n}\n"],"names":["AuthorizeResult"],"mappings":";;;;AAyBO,MAAM,cAA2C,CAAA;AAAA,EACtD,MAAM,MACJ,CAAA,QAAA,EACA,KACyB,EAAA;AACzB,IAAO,OAAA,EAAE,MAAQ,EAAAA,sCAAA,CAAgB,KAAM,EAAA,CAAA;AAAA,GACzC;AACF;;;;"}