@backstage-community/plugin-rbac-backend 7.4.1 → 7.4.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/CHANGELOG.md +7 -0
- package/dist/file-permissions/yaml-conditional-file-watcher.cjs.js +3 -3
- package/dist/file-permissions/yaml-conditional-file-watcher.cjs.js.map +1 -1
- package/dist/role-manager/ancestor-search-memo-sqlite.cjs.js +19 -12
- package/dist/role-manager/ancestor-search-memo-sqlite.cjs.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -51,7 +51,7 @@ class YamlConditinalPoliciesFileWatcher extends fileWatcher.AbstractFileWatcher
|
|
|
51
51
|
}
|
|
52
52
|
async onChange() {
|
|
53
53
|
try {
|
|
54
|
-
const newConds = this.parse()
|
|
54
|
+
const newConds = this.parse();
|
|
55
55
|
const addedConds = [];
|
|
56
56
|
const removedConds = [];
|
|
57
57
|
const csvFileRoles = await this.roleMetadataStorage.filterRoleMetadata("csv-file");
|
|
@@ -114,8 +114,8 @@ class YamlConditinalPoliciesFileWatcher extends fileWatcher.AbstractFileWatcher
|
|
|
114
114
|
*/
|
|
115
115
|
parse() {
|
|
116
116
|
const fileContents = this.getCurrentContents();
|
|
117
|
-
const data = yaml__default.default.loadAll(
|
|
118
|
-
|
|
117
|
+
const data = yaml__default.default.loadAll(fileContents).filter(
|
|
118
|
+
(doc) => doc !== null
|
|
119
119
|
);
|
|
120
120
|
for (const condition of data) {
|
|
121
121
|
conditionValidation.validateRoleCondition(condition);
|
|
@@ -1 +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 {\n AuditorService,\n AuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\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 { ActionType, ConditionEvents } from '../auditor/auditor';\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 auditor: AuditorService,\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 auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITIONAL_POLICIES_FILE_NOT_FOUND,\n severityLevel: 'medium',\n });\n await auditorEvent.fail({\n error: new Error(`File '${this.filePath}' was 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 =\n await this.roleMetadataStorage.filterRoleMetadata('csv-file');\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 const auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITIONAL_POLICIES_FILE_CHANGE,\n severityLevel: 'medium',\n });\n await auditorEvent.fail({\n 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 for (const condition of this.conditionsDiff.addedConditions) {\n const auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITION_WRITE,\n severityLevel: 'medium',\n meta: { actionType: ActionType.CREATE },\n });\n\n try {\n const conditionToCreate = await processConditionMapping(\n condition,\n this.pluginMetadataCollector,\n this.auth,\n );\n\n await this.conditionalStorage.createCondition(conditionToCreate);\n await auditorEvent.success({\n meta: { condition },\n });\n } catch (error) {\n await auditorEvent.fail({ error, meta: { condition } });\n }\n }\n\n this.conditionsDiff.addedConditions = [];\n }\n\n private async removeConditions(): Promise<void> {\n for (const condition of this.conditionsDiff.removedConditions) {\n const auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITION_WRITE,\n severityLevel: 'medium',\n meta: { actionType: ActionType.DELETE },\n });\n\n try {\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 await auditorEvent.success({ meta: { condition } });\n } catch (error) {\n await auditorEvent.fail({\n error,\n meta: { condition },\n });\n }\n }\n\n this.conditionsDiff.removedConditions = [];\n }\n\n async cleanUpConditionalPolicies(): Promise<void> {\n const csvFileRoles =\n await this.roleMetadataStorage.filterRoleMetadata('csv-file');\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","ActionType","processConditionMapping"],"mappings":";;;;;;;;;;;;;;;AA6CO,MAAM,0CAA0CA,+BAErD,CAAA;AAAA,EAGA,WAAA,CACE,UACA,WACA,EAAA,MAAA,EACiB,oBACA,OACA,EAAA,IAAA,EACA,uBACA,EAAA,mBAAA,EACA,gBACjB,EAAA;AACA,IAAM,KAAA,CAAA,QAAA,EAAU,aAAa,MAAM,CAAA;AAPlB,IAAA,IAAA,CAAA,kBAAA,GAAA,kBAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,uBAAA,GAAA,uBAAA;AACA,IAAA,IAAA,CAAA,mBAAA,GAAA,mBAAA;AACA,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA;AAIjB,IAAA,IAAA,CAAK,cAAiB,GAAA;AAAA,MACpB,iBAAiB,EAAC;AAAA,MAClB,mBAAmB;AAAC,KACtB;AAAA;AACF,EAnBQ,cAAA;AAAA,EAqBR,MAAM,UAA4B,GAAA;AAChC,IAAI,IAAA,CAAC,KAAK,QAAU,EAAA;AAClB,MAAA;AAAA;AAEF,IAAA,MAAM,UAAa,GAAAC,mBAAA,CAAG,UAAW,CAAA,IAAA,CAAK,QAAQ,CAAA;AAC9C,IAAA,IAAI,CAAC,UAAY,EAAA;AACf,MAAA,MAAM,YAAe,GAAA,MAAM,IAAK,CAAA,OAAA,CAAQ,WAAY,CAAA;AAAA,QAClD,SAASC,uBAAgB,CAAA,mCAAA;AAAA,QACzB,aAAe,EAAA;AAAA,OAChB,CAAA;AACD,MAAA,MAAM,aAAa,IAAK,CAAA;AAAA,QACtB,OAAO,IAAI,KAAA,CAAM,CAAS,MAAA,EAAA,IA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,QACH,mBAAmB,SAAU,CAAA,iBAAA,CAAkB,GAAI,CAAA,CAAA,EAAA,KAAM,GAAG,MAAM;AAAA,OACpE;AAAA,KACD,CAAA;AACD,IAAA,IAAA,CAAK,eAAe,iBAAoB,GAAA,gBAAA;AACxC,IAAA,MAAM,KAAK,gBAAiB,EAAA;AAAA;AAEhC;;;;"}
|
|
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 {\n AuditorService,\n AuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\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 { ActionType, ConditionEvents } from '../auditor/auditor';\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 auditor: AuditorService,\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 auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITIONAL_POLICIES_FILE_NOT_FOUND,\n severityLevel: 'medium',\n });\n await auditorEvent.fail({\n error: new Error(`File '${this.filePath}' was 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();\n\n const addedConds: RoleConditionalPolicyDecision<PermissionAction>[] = [];\n const removedConds: RoleConditionalPolicyDecision<PermissionAction>[] =\n [];\n\n const csvFileRoles =\n await this.roleMetadataStorage.filterRoleMetadata('csv-file');\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 const auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITIONAL_POLICIES_FILE_CHANGE,\n severityLevel: 'medium',\n });\n await auditorEvent.fail({\n 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\n .loadAll(fileContents)\n .filter(\n doc => doc !== null,\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 for (const condition of this.conditionsDiff.addedConditions) {\n const auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITION_WRITE,\n severityLevel: 'medium',\n meta: { actionType: ActionType.CREATE },\n });\n\n try {\n const conditionToCreate = await processConditionMapping(\n condition,\n this.pluginMetadataCollector,\n this.auth,\n );\n\n await this.conditionalStorage.createCondition(conditionToCreate);\n await auditorEvent.success({\n meta: { condition },\n });\n } catch (error) {\n await auditorEvent.fail({ error, meta: { condition } });\n }\n }\n\n this.conditionsDiff.addedConditions = [];\n }\n\n private async removeConditions(): Promise<void> {\n for (const condition of this.conditionsDiff.removedConditions) {\n const auditorEvent = await this.auditor.createEvent({\n eventId: ConditionEvents.CONDITION_WRITE,\n severityLevel: 'medium',\n meta: { actionType: ActionType.DELETE },\n });\n\n try {\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 await auditorEvent.success({ meta: { condition } });\n } catch (error) {\n await auditorEvent.fail({\n error,\n meta: { condition },\n });\n }\n }\n\n this.conditionsDiff.removedConditions = [];\n }\n\n async cleanUpConditionalPolicies(): Promise<void> {\n const csvFileRoles =\n await this.roleMetadataStorage.filterRoleMetadata('csv-file');\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","ActionType","processConditionMapping"],"mappings":";;;;;;;;;;;;;;;AA6CO,MAAM,0CAA0CA,+BAErD,CAAA;AAAA,EAGA,WAAA,CACE,UACA,WACA,EAAA,MAAA,EACiB,oBACA,OACA,EAAA,IAAA,EACA,uBACA,EAAA,mBAAA,EACA,gBACjB,EAAA;AACA,IAAM,KAAA,CAAA,QAAA,EAAU,aAAa,MAAM,CAAA;AAPlB,IAAA,IAAA,CAAA,kBAAA,GAAA,kBAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,uBAAA,GAAA,uBAAA;AACA,IAAA,IAAA,CAAA,mBAAA,GAAA,mBAAA;AACA,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA;AAIjB,IAAA,IAAA,CAAK,cAAiB,GAAA;AAAA,MACpB,iBAAiB,EAAC;AAAA,MAClB,mBAAmB;AAAC,KACtB;AA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A;AAAA,UACtB,KAAA;AAAA,UACA,IAAA,EAAM,EAAE,SAAU;AAAA,SACnB,CAAA;AAAA;AACH;AAGF,IAAK,IAAA,CAAA,cAAA,CAAe,oBAAoB,EAAC;AAAA;AAC3C,EAEA,MAAM,0BAA4C,GAAA;AAChD,IAAA,MAAM,YACJ,GAAA,MAAM,IAAK,CAAA,mBAAA,CAAoB,mBAAmB,UAAU,CAAA;AAC9D,IAAM,MAAA,gBAAA,GAAA,CACJ,MAAM,IAAA,CAAK,kBAAmB,CAAA,gBAAA;AAAA,MAC5B,YAAa,CAAA,GAAA,CAAI,CAAQ,IAAA,KAAA,IAAA,CAAK,aAAa;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;AAAA,OACpE;AAAA,KACD,CAAA;AACD,IAAA,IAAA,CAAK,eAAe,iBAAoB,GAAA,gBAAA;AACxC,IAAA,MAAM,KAAK,gBAAiB,EAAA;AAAA;AAEhC;;;;"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var catalogModel = require('@backstage/catalog-model');
|
|
3
4
|
var ancestorSearchMemo = require('./ancestor-search-memo.cjs.js');
|
|
4
5
|
|
|
5
6
|
class AncestorSearchMemoSQLite extends ancestorSearchMemo.AncestorSearchMemo {
|
|
@@ -18,7 +19,7 @@ class AncestorSearchMemoSQLite extends ancestorSearchMemo.AncestorSearchMemo {
|
|
|
18
19
|
const { items } = await this.catalogApi.getEntities(
|
|
19
20
|
{
|
|
20
21
|
filter: { kind: "Group" },
|
|
21
|
-
fields: ["metadata.name", "metadata.namespace", "spec.parent"]
|
|
22
|
+
fields: ["kind", "metadata.name", "metadata.namespace", "spec.parent"]
|
|
22
23
|
},
|
|
23
24
|
{ token }
|
|
24
25
|
);
|
|
@@ -32,30 +33,36 @@ class AncestorSearchMemoSQLite extends ancestorSearchMemo.AncestorSearchMemo {
|
|
|
32
33
|
const { items } = await this.catalogApi.getEntities(
|
|
33
34
|
{
|
|
34
35
|
filter: { kind: "Group", "relations.hasMember": this.userEntityRef },
|
|
35
|
-
fields: ["metadata.name", "metadata.namespace", "spec.parent"]
|
|
36
|
+
fields: ["kind", "metadata.name", "metadata.namespace", "spec.parent"]
|
|
36
37
|
},
|
|
37
38
|
{ token }
|
|
38
39
|
);
|
|
39
40
|
return items;
|
|
40
41
|
}
|
|
41
42
|
traverse(group, allGroups, current_depth) {
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (!super.hasEntityRef(groupName)) {
|
|
46
|
-
super.setNode(groupName);
|
|
43
|
+
const groupRef = catalogModel.stringifyEntityRef(group);
|
|
44
|
+
if (!super.hasEntityRef(groupRef)) {
|
|
45
|
+
super.setNode(groupRef);
|
|
47
46
|
}
|
|
48
47
|
if (this.maxDepth !== undefined && current_depth >= this.maxDepth) {
|
|
49
48
|
return;
|
|
50
49
|
}
|
|
51
50
|
const depth = current_depth + 1;
|
|
52
51
|
const parent = group.spec?.parent;
|
|
53
|
-
|
|
52
|
+
if (!parent) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const parentRef = catalogModel.stringifyEntityRef(
|
|
56
|
+
catalogModel.parseEntityRef(parent, {
|
|
57
|
+
defaultKind: "group",
|
|
58
|
+
defaultNamespace: group.metadata.namespace
|
|
59
|
+
})
|
|
60
|
+
);
|
|
61
|
+
const parentGroup = allGroups.find(
|
|
62
|
+
(g) => catalogModel.stringifyEntityRef(g) === parentRef
|
|
63
|
+
);
|
|
54
64
|
if (parentGroup) {
|
|
55
|
-
|
|
56
|
-
"en-US"
|
|
57
|
-
)}/${parentGroup.metadata.name.toLocaleLowerCase("en-US")}`;
|
|
58
|
-
super.setEdge(parentName, groupName);
|
|
65
|
+
super.setEdge(parentRef, groupRef);
|
|
59
66
|
if (super.isAcyclic()) {
|
|
60
67
|
this.traverse(parentGroup, allGroups, depth);
|
|
61
68
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ancestor-search-memo-sqlite.cjs.js","sources":["../../src/role-manager/ancestor-search-memo-sqlite.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 } from '@backstage/backend-plugin-api';\nimport type { CatalogApi } from '@backstage/catalog-client';\nimport type { Entity } from '@backstage/catalog-model';\n\nimport { AncestorSearchMemo } from './ancestor-search-memo';\n\nexport class AncestorSearchMemoSQLite extends AncestorSearchMemo<Entity> {\n constructor(\n private readonly userEntityRef: string,\n private readonly catalogApi: CatalogApi,\n private readonly auth: AuthService,\n private readonly maxDepth?: number,\n ) {\n super();\n }\n\n async getAllASMGroups(): Promise<Entity[]> {\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const { items } = await this.catalogApi.getEntities(\n {\n filter: { kind: 'Group' },\n fields: ['metadata.name', 'metadata.namespace', 'spec.parent'],\n },\n { token },\n );\n return items;\n }\n\n async getUserASMGroups(): Promise<Entity[]> {\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n const { items } = await this.catalogApi.getEntities(\n {\n filter: { kind: 'Group', 'relations.hasMember': this.userEntityRef },\n fields: ['metadata.name', 'metadata.namespace', 'spec.parent'],\n },\n { token },\n );\n return items;\n }\n\n traverse(group: Entity, allGroups: Entity[], current_depth: number) {\n const
|
|
1
|
+
{"version":3,"file":"ancestor-search-memo-sqlite.cjs.js","sources":["../../src/role-manager/ancestor-search-memo-sqlite.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 } from '@backstage/backend-plugin-api';\nimport type { CatalogApi } from '@backstage/catalog-client';\nimport type { Entity } from '@backstage/catalog-model';\nimport { parseEntityRef, stringifyEntityRef } from '@backstage/catalog-model';\n\nimport { AncestorSearchMemo } from './ancestor-search-memo';\n\nexport class AncestorSearchMemoSQLite extends AncestorSearchMemo<Entity> {\n constructor(\n private readonly userEntityRef: string,\n private readonly catalogApi: CatalogApi,\n private readonly auth: AuthService,\n private readonly maxDepth?: number,\n ) {\n super();\n }\n\n async getAllASMGroups(): Promise<Entity[]> {\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const { items } = await this.catalogApi.getEntities(\n {\n filter: { kind: 'Group' },\n fields: ['kind', 'metadata.name', 'metadata.namespace', 'spec.parent'],\n },\n { token },\n );\n return items;\n }\n\n async getUserASMGroups(): Promise<Entity[]> {\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n const { items } = await this.catalogApi.getEntities(\n {\n filter: { kind: 'Group', 'relations.hasMember': this.userEntityRef },\n fields: ['kind', 'metadata.name', 'metadata.namespace', 'spec.parent'],\n },\n { token },\n );\n return items;\n }\n\n traverse(group: Entity, allGroups: Entity[], current_depth: number) {\n const groupRef = stringifyEntityRef(group);\n\n if (!super.hasEntityRef(groupRef)) {\n super.setNode(groupRef);\n }\n\n if (this.maxDepth !== undefined && current_depth >= this.maxDepth) {\n return;\n }\n const depth = current_depth + 1;\n\n const parent = group.spec?.parent as string;\n if (!parent) {\n return;\n }\n\n const parentRef = stringifyEntityRef(\n parseEntityRef(parent, {\n defaultKind: 'group',\n defaultNamespace: group.metadata.namespace,\n }),\n );\n\n const parentGroup = allGroups.find(\n g => stringifyEntityRef(g) === parentRef,\n );\n\n if (parentGroup) {\n super.setEdge(parentRef, groupRef);\n\n if (super.isAcyclic()) {\n this.traverse(parentGroup, allGroups, depth);\n }\n }\n }\n\n async buildUserGraph() {\n const userGroups = await this.getUserASMGroups();\n const allGroups = await this.getAllASMGroups();\n userGroups.forEach(group =>\n this.traverse(group as Entity, allGroups as Entity[], 0),\n );\n }\n}\n"],"names":["AncestorSearchMemo","stringifyEntityRef","parseEntityRef"],"mappings":";;;;;AAsBO,MAAM,iCAAiCA,qCAA2B,CAAA;AAAA,EACvE,WACmB,CAAA,aAAA,EACA,UACA,EAAA,IAAA,EACA,QACjB,EAAA;AACA,IAAM,KAAA,EAAA;AALW,IAAA,IAAA,CAAA,aAAA,GAAA,aAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA;AAGnB,EAEA,MAAM,eAAqC,GAAA;AACzC,IAAA,MAAM,EAAE,KAAM,EAAA,GAAI,MAAM,IAAA,CAAK,KAAK,qBAAsB,CAAA;AAAA,MACtD,UAAY,EAAA,MAAM,IAAK,CAAA,IAAA,CAAK,wBAAyB,EAAA;AAAA,MACrD,cAAgB,EAAA;AAAA,KACjB,CAAA;AAED,IAAA,MAAM,EAAE,KAAA,EAAU,GAAA,MAAM,KAAK,UAAW,CAAA,WAAA;AAAA,MACt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