@backstage/plugin-permission-node 0.0.0-nightly-2021102522541

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 ADDED
@@ -0,0 +1,12 @@
1
+ # @backstage/plugin-permission-node
2
+
3
+ ## 0.0.0-nightly-2021102522541
4
+ ### Minor Changes
5
+
6
+ - 44b46644d9: New package containing common permission and authorization utilities for backend plugins. For more information, see the [authorization PRFC](https://github.com/backstage/backstage/pull/7761).
7
+
8
+ ### Patch Changes
9
+
10
+ - Updated dependencies
11
+ - @backstage/plugin-auth-backend@0.0.0-nightly-2021102522541
12
+ - @backstage/plugin-permission-common@0.0.0-nightly-2021102522541
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @backstage/plugin-permission-node
2
+
3
+ > NOTE: THIS PACKAGE IS EXPERIMENTAL, HERE BE DRAGONS
4
+
5
+ Common permission and authorization utilities for backend plugins. For more
6
+ information, see the [authorization
7
+ PRFC](https://github.com/backstage/backstage/pull/7761).
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var express = require('express');
6
+ var zod = require('zod');
7
+ var pluginPermissionCommon = require('@backstage/plugin-permission-common');
8
+
9
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
+
11
+ var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
12
+
13
+ const createConditionFactory = (rule) => (...params) => ({
14
+ rule: rule.name,
15
+ params
16
+ });
17
+
18
+ const createConditionExports = (options) => {
19
+ const {pluginId, resourceType, rules} = options;
20
+ return {
21
+ conditions: Object.entries(rules).reduce((acc, [key, rule]) => ({
22
+ ...acc,
23
+ [key]: createConditionFactory(rule)
24
+ }), {}),
25
+ createConditions: (conditions) => ({
26
+ pluginId,
27
+ resourceType,
28
+ conditions
29
+ })
30
+ };
31
+ };
32
+
33
+ const isAndCriteria = (filter) => Object.prototype.hasOwnProperty.call(filter, "allOf");
34
+ const isOrCriteria = (filter) => Object.prototype.hasOwnProperty.call(filter, "anyOf");
35
+ const isNotCriteria = (filter) => Object.prototype.hasOwnProperty.call(filter, "not");
36
+ const createGetRule = (rules) => {
37
+ const rulesMap = new Map(Object.values(rules).map((rule) => [rule.name, rule]));
38
+ return (name) => {
39
+ const rule = rulesMap.get(name);
40
+ if (!rule) {
41
+ throw new Error(`Unexpected permission rule: ${name}`);
42
+ }
43
+ return rule;
44
+ };
45
+ };
46
+
47
+ const mapConditions = (criteria, getRule) => {
48
+ if (isAndCriteria(criteria)) {
49
+ return {
50
+ allOf: criteria.allOf.map((child) => mapConditions(child, getRule))
51
+ };
52
+ } else if (isOrCriteria(criteria)) {
53
+ return {
54
+ anyOf: criteria.anyOf.map((child) => mapConditions(child, getRule))
55
+ };
56
+ } else if (isNotCriteria(criteria)) {
57
+ return {
58
+ not: mapConditions(criteria.not, getRule)
59
+ };
60
+ }
61
+ return getRule(criteria.rule).toQuery(...criteria.params);
62
+ };
63
+ const createConditionTransformer = (permissionRules) => {
64
+ const getRule = createGetRule(permissionRules);
65
+ return (conditions) => mapConditions(conditions, getRule);
66
+ };
67
+
68
+ const permissionCriteriaSchema = zod.z.lazy(() => zod.z.union([
69
+ zod.z.object({anyOf: zod.z.array(permissionCriteriaSchema)}),
70
+ zod.z.object({allOf: zod.z.array(permissionCriteriaSchema)}),
71
+ zod.z.object({not: permissionCriteriaSchema}),
72
+ zod.z.object({
73
+ rule: zod.z.string(),
74
+ params: zod.z.array(zod.z.unknown())
75
+ })
76
+ ]));
77
+ const applyConditionsRequestSchema = zod.z.object({
78
+ resourceRef: zod.z.string(),
79
+ resourceType: zod.z.string(),
80
+ conditions: permissionCriteriaSchema
81
+ });
82
+ const applyConditions = (criteria, resource, getRule) => {
83
+ if (isAndCriteria(criteria)) {
84
+ return criteria.allOf.every((child) => applyConditions(child, resource, getRule));
85
+ } else if (isOrCriteria(criteria)) {
86
+ return criteria.anyOf.some((child) => applyConditions(child, resource, getRule));
87
+ } else if (isNotCriteria(criteria)) {
88
+ return !applyConditions(criteria.not, resource, getRule);
89
+ }
90
+ return getRule(criteria.rule).apply(resource, ...criteria.params);
91
+ };
92
+ const createPermissionIntegrationRouter = ({
93
+ resourceType,
94
+ rules,
95
+ getResource
96
+ }) => {
97
+ const router = express.Router();
98
+ const getRule = createGetRule(rules);
99
+ router.post("/permissions/apply-conditions", express__default['default'].json(), async (req, res) => {
100
+ const parseResult = applyConditionsRequestSchema.safeParse(req.body);
101
+ if (!parseResult.success) {
102
+ return res.status(400).send(`Invalid request body.`);
103
+ }
104
+ const {data: body} = parseResult;
105
+ if (body.resourceType !== resourceType) {
106
+ return res.status(400).send(`Unexpected resource type: ${body.resourceType}.`);
107
+ }
108
+ const resource = await getResource(body.resourceRef);
109
+ if (!resource) {
110
+ return res.status(400).send(`Resource for ref ${body.resourceRef} not found.`);
111
+ }
112
+ return res.status(200).json({
113
+ result: applyConditions(body.conditions, resource, getRule) ? pluginPermissionCommon.AuthorizeResult.ALLOW : pluginPermissionCommon.AuthorizeResult.DENY
114
+ });
115
+ });
116
+ return router;
117
+ };
118
+
119
+ exports.createConditionExports = createConditionExports;
120
+ exports.createConditionFactory = createConditionFactory;
121
+ exports.createConditionTransformer = createConditionTransformer;
122
+ exports.createPermissionIntegrationRouter = createPermissionIntegrationRouter;
123
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/integration/createConditionFactory.ts","../src/integration/createConditionExports.ts","../src/integration/util.ts","../src/integration/createConditionTransformer.ts","../src/integration/createPermissionIntegrationRouter.ts"],"sourcesContent":["/*\n * Copyright 2021 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 */\n\nimport { PermissionRule } from '../types';\n\n/**\n * Creates a condition factory function for a given authorization rule and parameter types.\n *\n * @remarks\n *\n * For example, an isEntityOwner rule for catalog entities might take an array of entityRef strings.\n * The rule itself defines _how_ to check a given resource, whereas a condition also includes _what_\n * to verify.\n *\n * Plugin authors should generally use the {@link createConditionExports} in order to efficiently\n * create multiple condition factories. This helper should generally only be used to construct\n * condition factories for third-party rules that aren't part of the backend plugin with which\n * they're intended to integrate.\n *\n * @public\n */\nexport const createConditionFactory =\n <TParams extends any[]>(rule: PermissionRule<unknown, unknown, TParams>) =>\n (...params: TParams) => ({\n rule: rule.name,\n params,\n });\n","/*\n * Copyright 2021 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 */\n\nimport {\n PermissionCondition,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport { createConditionFactory } from './createConditionFactory';\n\n/**\n * A utility type for mapping a single {@link PermissionRule} to its\n * corresponding {@link @backstage/plugin-permission-common#PermissionCondition}.\n *\n * @public\n */\nexport type Condition<TRule> = TRule extends PermissionRule<\n any,\n any,\n infer TParams\n>\n ? (...params: TParams) => PermissionCondition<TParams>\n : never;\n\n/**\n * A utility type for mapping {@link PermissionRule}s to their corresponding\n * {@link @backstage/plugin-permission-common#PermissionCondition}s.\n *\n * @public\n */\nexport type Conditions<\n TRules extends Record<string, PermissionRule<any, any>>,\n> = {\n [Name in keyof TRules]: Condition<TRules[Name]>;\n};\n\n/**\n * Creates the recommended condition-related exports for a given plugin based on the built-in\n * {@link PermissionRule}s it supports.\n *\n * @remarks\n *\n * The function returns a `conditions` object containing a\n * {@link @backstage/plugin-permission-common#PermissionCondition} factory for each of the\n * supplied {@link PermissionRule}s, along with a `createConditions` function which builds the\n * wrapper object needed to enclose conditions when authoring {@link PermissionPolicy} implementations.\n *\n * Plugin authors should generally call this method with all the built-in {@link PermissionRule}s\n * the plugin supports, and export the resulting `conditions` object and `createConditions`\n * function so that they can be used by {@link PermissionPolicy} authors.\n *\n * @public\n */\nexport const createConditionExports = <\n TResource,\n TRules extends Record<string, PermissionRule<TResource, any>>,\n>(options: {\n pluginId: string;\n resourceType: string;\n rules: TRules;\n}): {\n conditions: Conditions<TRules>;\n createConditions: (conditions: PermissionCriteria<PermissionCondition>) => {\n pluginId: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n };\n} => {\n const { pluginId, resourceType, rules } = options;\n\n return {\n conditions: Object.entries(rules).reduce(\n (acc, [key, rule]) => ({\n ...acc,\n [key]: createConditionFactory(rule),\n }),\n {} as Conditions<TRules>,\n ),\n createConditions: (\n conditions: PermissionCriteria<PermissionCondition>,\n ) => ({\n pluginId,\n resourceType,\n conditions,\n }),\n };\n};\n","/*\n * Copyright 2021 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 */\n\nimport { PermissionCriteria } from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\nexport const isAndCriteria = (\n filter: PermissionCriteria<unknown>,\n): filter is { allOf: PermissionCriteria<unknown>[] } =>\n Object.prototype.hasOwnProperty.call(filter, 'allOf');\n\nexport const isOrCriteria = (\n filter: PermissionCriteria<unknown>,\n): filter is { anyOf: PermissionCriteria<unknown>[] } =>\n Object.prototype.hasOwnProperty.call(filter, 'anyOf');\n\nexport const isNotCriteria = (\n filter: PermissionCriteria<unknown>,\n): filter is { not: PermissionCriteria<unknown> } =>\n Object.prototype.hasOwnProperty.call(filter, 'not');\n\nexport const createGetRule = <TResource, TQuery>(\n rules: PermissionRule<TResource, TQuery>[],\n) => {\n const rulesMap = new Map(Object.values(rules).map(rule => [rule.name, rule]));\n\n return (name: string): PermissionRule<TResource, TQuery> => {\n const rule = rulesMap.get(name);\n\n if (!rule) {\n throw new Error(`Unexpected permission rule: ${name}`);\n }\n\n return rule;\n };\n};\n","/*\n * Copyright 2021 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 PermissionCondition,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport {\n createGetRule,\n isAndCriteria,\n isNotCriteria,\n isOrCriteria,\n} from './util';\n\nconst mapConditions = <TQuery>(\n criteria: PermissionCriteria<PermissionCondition>,\n getRule: (name: string) => PermissionRule<unknown, TQuery>,\n): PermissionCriteria<TQuery> => {\n if (isAndCriteria(criteria)) {\n return {\n allOf: criteria.allOf.map(child => mapConditions(child, getRule)),\n };\n } else if (isOrCriteria(criteria)) {\n return {\n anyOf: criteria.anyOf.map(child => mapConditions(child, getRule)),\n };\n } else if (isNotCriteria(criteria)) {\n return {\n not: mapConditions(criteria.not, getRule),\n };\n }\n\n return getRule(criteria.rule).toQuery(...criteria.params);\n};\n\n/**\n * A function which accepts {@link @backstage/plugin-permission-common#PermissionCondition}s\n * logically grouped in a {@link @backstage/plugin-permission-common#PermissionCriteria}\n * object, and transforms the {@link @backstage/plugin-permission-common#PermissionCondition}s\n * into plugin specific query fragments while retaining the enclosing criteria shape.\n *\n * @public\n */\nexport type ConditionTransformer<TQuery> = (\n conditions: PermissionCriteria<PermissionCondition>,\n) => PermissionCriteria<TQuery>;\n\n/**\n * A higher-order helper function which accepts an array of\n * {@link PermissionRule}s, and returns a {@link ConditionTransformer}\n * which transforms input conditions into equivalent plugin-specific\n * query fragments using the supplied rules.\n *\n * @public\n */\nexport const createConditionTransformer = <\n TQuery,\n TRules extends PermissionRule<any, TQuery>[],\n>(\n permissionRules: [...TRules],\n): ConditionTransformer<TQuery> => {\n const getRule = createGetRule(permissionRules);\n\n return conditions => mapConditions(conditions, getRule);\n};\n","/*\n * Copyright 2021 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 */\n\nimport express, { Response, Router } from 'express';\nimport { z } from 'zod';\nimport {\n AuthorizeResult,\n PermissionCondition,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport {\n createGetRule,\n isAndCriteria,\n isNotCriteria,\n isOrCriteria,\n} from './util';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z.union([\n z.object({ anyOf: z.array(permissionCriteriaSchema) }),\n z.object({ allOf: z.array(permissionCriteriaSchema) }),\n z.object({ not: permissionCriteriaSchema }),\n z.object({\n rule: z.string(),\n params: z.array(z.unknown()),\n }),\n ]),\n);\n\nconst applyConditionsRequestSchema = z.object({\n resourceRef: z.string(),\n resourceType: z.string(),\n conditions: permissionCriteriaSchema,\n});\n\n/**\n * A request to load the referenced resource and apply conditions in order to\n * finalize a conditional authorization response.\n *\n * @public\n */\nexport type ApplyConditionsRequest = {\n resourceRef: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n};\n\n/**\n * The result of applying the conditions, expressed as a definitive authorize\n * result of ALLOW or DENY.\n *\n * @public\n */\nexport type ApplyConditionsResponse = {\n result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;\n};\n\nconst applyConditions = <TResource>(\n criteria: PermissionCriteria<PermissionCondition>,\n resource: TResource,\n getRule: (name: string) => PermissionRule<TResource, unknown>,\n): boolean => {\n if (isAndCriteria(criteria)) {\n return criteria.allOf.every(child =>\n applyConditions(child, resource, getRule),\n );\n } else if (isOrCriteria(criteria)) {\n return criteria.anyOf.some(child =>\n applyConditions(child, resource, getRule),\n );\n } else if (isNotCriteria(criteria)) {\n return !applyConditions(criteria.not, resource, getRule);\n }\n\n return getRule(criteria.rule).apply(resource, ...criteria.params);\n};\n\n/**\n * Create an express Router which provides an authorization route to allow integration between the\n * permission backend and other Backstage backend plugins. Plugin owners that wish to support\n * conditional authorization for their resources should add the router created by this function\n * to their express app inside their `createRouter` implementation.\n *\n * @remarks\n *\n * To make this concrete, we can use the Backstage software catalog as an example. The catalog has\n * conditional rules around access to specific _entities_ in the catalog. The _type_ of resource is\n * captured here as `resourceType`, a string identifier (`catalog-entity` in this example) that can\n * be provided with permission definitions. This is merely a _type_ to verify that conditions in an\n * authorization policy are constructed correctly, not a reference to a specific resource.\n *\n * The `rules` parameter is an array of {@link PermissionRule}s that introduce conditional\n * filtering logic for resources; for the catalog, these are things like `isEntityOwner` or\n * `hasAnnotation`. Rules describe how to filter a list of resources, and the `conditions` returned\n * allow these rules to be applied with specific parameters (such as 'group:default/team-a', or\n * 'backstage.io/edit-url').\n *\n * The `getResource` argument should load a resource by reference. For the catalog, this is an\n * {@link @backstage/catalog-model#EntityRef}. For other plugins, this can be any serialized format.\n * This is used to construct the `createPermissionIntegrationRouter`, a function to add an\n * authorization route to your backend plugin. This route will be called by the `permission-backend`\n * when authorization conditions relating to this plugin need to be evaluated.\n * @public\n */\nexport const createPermissionIntegrationRouter = <TResource>({\n resourceType,\n rules,\n getResource,\n}: {\n resourceType: string;\n rules: PermissionRule<TResource, any>[];\n getResource: (resourceRef: string) => Promise<TResource | undefined>;\n}): Router => {\n const router = Router();\n\n const getRule = createGetRule(rules);\n\n router.post(\n '/permissions/apply-conditions',\n express.json(),\n async (\n req,\n res: Response<\n | {\n result: Omit<AuthorizeResult, AuthorizeResult.CONDITIONAL>;\n }\n | string\n >,\n ) => {\n const parseResult = applyConditionsRequestSchema.safeParse(req.body);\n\n if (!parseResult.success) {\n return res.status(400).send(`Invalid request body.`);\n }\n\n const { data: body } = parseResult;\n\n if (body.resourceType !== resourceType) {\n return res\n .status(400)\n .send(`Unexpected resource type: ${body.resourceType}.`);\n }\n\n const resource = await getResource(body.resourceRef);\n\n if (!resource) {\n return res\n .status(400)\n .send(`Resource for ref ${body.resourceRef} not found.`);\n }\n\n return res.status(200).json({\n result: applyConditions(body.conditions, resource, getRule)\n ? AuthorizeResult.ALLOW\n : AuthorizeResult.DENY,\n });\n },\n );\n\n return router;\n};\n"],"names":["z","Router","express","AuthorizeResult"],"mappings":"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"}
@@ -0,0 +1,238 @@
1
+ import { PermissionCriteria, PermissionCondition, AuthorizeResult, AuthorizeRequest } from '@backstage/plugin-permission-common';
2
+ import { Router } from 'express';
3
+ import { BackstageIdentity } from '@backstage/plugin-auth-backend';
4
+
5
+ /**
6
+ * A conditional rule that can be provided in an
7
+ * {@link @backstage/permission-common#AuthorizeResult} response to an authorization request.
8
+ *
9
+ * @remarks
10
+ *
11
+ * Rules can either be evaluated against a resource loaded in memory, or used as filters when
12
+ * loading a collection of resources from a data source. The `apply` and `toQuery` methods implement
13
+ * these two concepts.
14
+ *
15
+ * The two operations should always have the same logical result. If they don’t, the effective
16
+ * outcome of an authorization operation will sometimes differ depending on how the authorization
17
+ * check was performed.
18
+ *
19
+ * @public
20
+ */
21
+ declare type PermissionRule<TResource, TQuery, TParams extends unknown[] = unknown[]> = {
22
+ name: string;
23
+ description: string;
24
+ /**
25
+ * Apply this rule to a resource already loaded from a backing data source. The params are
26
+ * arguments supplied for the rule; for example, a rule could be `isOwner` with entityRefs as the
27
+ * params.
28
+ */
29
+ apply(resource: TResource, ...params: TParams): boolean;
30
+ /**
31
+ * Translate this rule to criteria suitable for use in querying a backing data store. The criteria
32
+ * can be used for loading a collection of resources efficiently with conditional criteria already
33
+ * applied.
34
+ */
35
+ toQuery(...params: TParams): PermissionCriteria<TQuery>;
36
+ };
37
+
38
+ /**
39
+ * Creates a condition factory function for a given authorization rule and parameter types.
40
+ *
41
+ * @remarks
42
+ *
43
+ * For example, an isEntityOwner rule for catalog entities might take an array of entityRef strings.
44
+ * The rule itself defines _how_ to check a given resource, whereas a condition also includes _what_
45
+ * to verify.
46
+ *
47
+ * Plugin authors should generally use the {@link createConditionExports} in order to efficiently
48
+ * create multiple condition factories. This helper should generally only be used to construct
49
+ * condition factories for third-party rules that aren't part of the backend plugin with which
50
+ * they're intended to integrate.
51
+ *
52
+ * @public
53
+ */
54
+ declare const createConditionFactory: <TParams extends any[]>(rule: PermissionRule<unknown, unknown, TParams>) => (...params: TParams) => {
55
+ rule: string;
56
+ params: TParams;
57
+ };
58
+
59
+ /**
60
+ * A utility type for mapping a single {@link PermissionRule} to its
61
+ * corresponding {@link @backstage/plugin-permission-common#PermissionCondition}.
62
+ *
63
+ * @public
64
+ */
65
+ declare type Condition<TRule> = TRule extends PermissionRule<any, any, infer TParams> ? (...params: TParams) => PermissionCondition<TParams> : never;
66
+ /**
67
+ * A utility type for mapping {@link PermissionRule}s to their corresponding
68
+ * {@link @backstage/plugin-permission-common#PermissionCondition}s.
69
+ *
70
+ * @public
71
+ */
72
+ declare type Conditions<TRules extends Record<string, PermissionRule<any, any>>> = {
73
+ [Name in keyof TRules]: Condition<TRules[Name]>;
74
+ };
75
+ /**
76
+ * Creates the recommended condition-related exports for a given plugin based on the built-in
77
+ * {@link PermissionRule}s it supports.
78
+ *
79
+ * @remarks
80
+ *
81
+ * The function returns a `conditions` object containing a
82
+ * {@link @backstage/plugin-permission-common#PermissionCondition} factory for each of the
83
+ * supplied {@link PermissionRule}s, along with a `createConditions` function which builds the
84
+ * wrapper object needed to enclose conditions when authoring {@link PermissionPolicy} implementations.
85
+ *
86
+ * Plugin authors should generally call this method with all the built-in {@link PermissionRule}s
87
+ * the plugin supports, and export the resulting `conditions` object and `createConditions`
88
+ * function so that they can be used by {@link PermissionPolicy} authors.
89
+ *
90
+ * @public
91
+ */
92
+ declare const createConditionExports: <TResource, TRules extends Record<string, PermissionRule<TResource, any, unknown[]>>>(options: {
93
+ pluginId: string;
94
+ resourceType: string;
95
+ rules: TRules;
96
+ }) => {
97
+ conditions: Conditions<TRules>;
98
+ createConditions: (conditions: PermissionCriteria<PermissionCondition>) => {
99
+ pluginId: string;
100
+ resourceType: string;
101
+ conditions: PermissionCriteria<PermissionCondition>;
102
+ };
103
+ };
104
+
105
+ /**
106
+ * A function which accepts {@link @backstage/plugin-permission-common#PermissionCondition}s
107
+ * logically grouped in a {@link @backstage/plugin-permission-common#PermissionCriteria}
108
+ * object, and transforms the {@link @backstage/plugin-permission-common#PermissionCondition}s
109
+ * into plugin specific query fragments while retaining the enclosing criteria shape.
110
+ *
111
+ * @public
112
+ */
113
+ declare type ConditionTransformer<TQuery> = (conditions: PermissionCriteria<PermissionCondition>) => PermissionCriteria<TQuery>;
114
+ /**
115
+ * A higher-order helper function which accepts an array of
116
+ * {@link PermissionRule}s, and returns a {@link ConditionTransformer}
117
+ * which transforms input conditions into equivalent plugin-specific
118
+ * query fragments using the supplied rules.
119
+ *
120
+ * @public
121
+ */
122
+ declare const createConditionTransformer: <TQuery, TRules extends PermissionRule<any, TQuery, unknown[]>[]>(permissionRules: [...TRules]) => ConditionTransformer<TQuery>;
123
+
124
+ /**
125
+ * A request to load the referenced resource and apply conditions in order to
126
+ * finalize a conditional authorization response.
127
+ *
128
+ * @public
129
+ */
130
+ declare type ApplyConditionsRequest = {
131
+ resourceRef: string;
132
+ resourceType: string;
133
+ conditions: PermissionCriteria<PermissionCondition>;
134
+ };
135
+ /**
136
+ * The result of applying the conditions, expressed as a definitive authorize
137
+ * result of ALLOW or DENY.
138
+ *
139
+ * @public
140
+ */
141
+ declare type ApplyConditionsResponse = {
142
+ result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;
143
+ };
144
+ /**
145
+ * Create an express Router which provides an authorization route to allow integration between the
146
+ * permission backend and other Backstage backend plugins. Plugin owners that wish to support
147
+ * conditional authorization for their resources should add the router created by this function
148
+ * to their express app inside their `createRouter` implementation.
149
+ *
150
+ * @remarks
151
+ *
152
+ * To make this concrete, we can use the Backstage software catalog as an example. The catalog has
153
+ * conditional rules around access to specific _entities_ in the catalog. The _type_ of resource is
154
+ * captured here as `resourceType`, a string identifier (`catalog-entity` in this example) that can
155
+ * be provided with permission definitions. This is merely a _type_ to verify that conditions in an
156
+ * authorization policy are constructed correctly, not a reference to a specific resource.
157
+ *
158
+ * The `rules` parameter is an array of {@link PermissionRule}s that introduce conditional
159
+ * filtering logic for resources; for the catalog, these are things like `isEntityOwner` or
160
+ * `hasAnnotation`. Rules describe how to filter a list of resources, and the `conditions` returned
161
+ * allow these rules to be applied with specific parameters (such as 'group:default/team-a', or
162
+ * 'backstage.io/edit-url').
163
+ *
164
+ * The `getResource` argument should load a resource by reference. For the catalog, this is an
165
+ * {@link @backstage/catalog-model#EntityRef}. For other plugins, this can be any serialized format.
166
+ * This is used to construct the `createPermissionIntegrationRouter`, a function to add an
167
+ * authorization route to your backend plugin. This route will be called by the `permission-backend`
168
+ * when authorization conditions relating to this plugin need to be evaluated.
169
+ * @public
170
+ */
171
+ declare const createPermissionIntegrationRouter: <TResource>({ resourceType, rules, getResource, }: {
172
+ resourceType: string;
173
+ rules: PermissionRule<TResource, any, unknown[]>[];
174
+ getResource: (resourceRef: string) => Promise<TResource | undefined>;
175
+ }) => Router;
176
+
177
+ /**
178
+ * An authorization request to be evaluated by the {@link PermissionPolicy}.
179
+ *
180
+ * @remarks
181
+ *
182
+ * This differs from {@link @backstage/permission-common#AuthorizeRequest} in that `resourceRef`
183
+ * should never be provided. This forces policies to be written in a way that's compatible with
184
+ * filtering collections of resources at data load time.
185
+ *
186
+ * @public
187
+ */
188
+ declare type PolicyAuthorizeRequest = Omit<AuthorizeRequest, 'resourceRef'>;
189
+ /**
190
+ * A conditional result to an authorization request, returned by the {@link PermissionPolicy}.
191
+ *
192
+ * @remarks
193
+ *
194
+ * This indicates that the policy allows authorization for the request, given that the returned
195
+ * conditions hold when evaluated. The conditions will be evaluated by the corresponding plugin
196
+ * which knows about the referenced permission rules.
197
+ *
198
+ * Similar to {@link @backstage/permission-common#AuthorizeResult}, but with the plugin and resource
199
+ * identifiers needed to evaluate the returned conditions.
200
+ * @public
201
+ */
202
+ declare type ConditionalPolicyResult = {
203
+ result: AuthorizeResult.CONDITIONAL;
204
+ conditions: {
205
+ pluginId: string;
206
+ resourceType: string;
207
+ conditions: PermissionCriteria<PermissionCondition>;
208
+ };
209
+ };
210
+ /**
211
+ * The result of evaluating an authorization request with a {@link PermissionPolicy}.
212
+ *
213
+ * @public
214
+ */
215
+ declare type PolicyResult = {
216
+ result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;
217
+ } | ConditionalPolicyResult;
218
+ /**
219
+ * A policy to evaluate authorization requests for any permissioned action performed in Backstage.
220
+ *
221
+ * @remarks
222
+ *
223
+ * This takes as input a permission and an optional Backstage identity, and should return ALLOW if
224
+ * the user is permitted to execute that action; otherwise DENY. For permissions relating to
225
+ * resources, such a catalog entities, a conditional response can also be returned. This states
226
+ * that the action is allowed if the conditions provided hold true.
227
+ *
228
+ * Conditions are a rule, and parameters to evaluate against that rule. For example, the rule might
229
+ * be `isOwner` and the parameters a collection of entityRefs; if one of the entityRefs matches
230
+ * the `owner` field on a catalog entity, this would resolve to ALLOW.
231
+ *
232
+ * @public
233
+ */
234
+ interface PermissionPolicy {
235
+ handle(request: PolicyAuthorizeRequest, user?: BackstageIdentity): Promise<PolicyResult>;
236
+ }
237
+
238
+ export { ApplyConditionsRequest, ApplyConditionsResponse, Condition, ConditionTransformer, ConditionalPolicyResult, Conditions, PermissionPolicy, PermissionRule, PolicyAuthorizeRequest, PolicyResult, createConditionExports, createConditionFactory, createConditionTransformer, createPermissionIntegrationRouter };
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@backstage/plugin-permission-node",
3
+ "description": "Common permission and authorization utilities for backend plugins",
4
+ "version": "0.0.0-nightly-2021102522541",
5
+ "main": "dist/index.cjs.js",
6
+ "types": "dist/index.d.ts",
7
+ "license": "Apache-2.0",
8
+ "publishConfig": {
9
+ "access": "public",
10
+ "main": "dist/index.cjs.js",
11
+ "types": "dist/index.d.ts"
12
+ },
13
+ "homepage": "https://backstage.io",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/backstage/backstage",
17
+ "directory": "plugins/permission-node"
18
+ },
19
+ "keywords": [
20
+ "backstage",
21
+ "permissions"
22
+ ],
23
+ "scripts": {
24
+ "build": "backstage-cli backend:build",
25
+ "lint": "backstage-cli lint",
26
+ "test": "backstage-cli test",
27
+ "prepack": "backstage-cli prepack",
28
+ "postpack": "backstage-cli postpack",
29
+ "clean": "backstage-cli clean"
30
+ },
31
+ "dependencies": {
32
+ "@backstage/plugin-auth-backend": "^0.0.0-nightly-2021102522541",
33
+ "@backstage/plugin-permission-common": "^0.0.0-nightly-2021102522541",
34
+ "@types/express": "^4.17.6",
35
+ "express": "^4.17.1",
36
+ "zod": "^3.11.6"
37
+ },
38
+ "devDependencies": {
39
+ "@backstage/cli": "^0.0.0-nightly-2021102522541",
40
+ "@types/supertest": "^2.0.8",
41
+ "supertest": "^6.1.3"
42
+ },
43
+ "files": [
44
+ "dist"
45
+ ]
46
+ }