@backstage/plugin-permission-backend 0.2.3 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/dist/index.cjs.js +51 -35
- package/dist/index.cjs.js.map +1 -1
- package/package.json +12 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,65 @@
|
|
|
1
1
|
# @backstage/plugin-permission-backend
|
|
2
2
|
|
|
3
|
+
## 0.4.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @backstage/plugin-auth-backend@0.8.0
|
|
9
|
+
- @backstage/backend-common@0.10.5
|
|
10
|
+
- @backstage/plugin-permission-node@0.4.1
|
|
11
|
+
|
|
12
|
+
## 0.4.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- b768259244: **BREAKING**: Wrap batched requests and responses to /authorize in an envelope object. The latest version of the PermissionClient in @backstage/permission-common uses the new format - as long as the permission-backend is consumed using this client, no other changes are necessary.
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- Updated dependencies
|
|
21
|
+
- @backstage/plugin-auth-backend@0.7.0
|
|
22
|
+
- @backstage/plugin-permission-common@0.4.0
|
|
23
|
+
- @backstage/backend-common@0.10.4
|
|
24
|
+
- @backstage/config@0.1.13
|
|
25
|
+
- @backstage/plugin-permission-node@0.4.0
|
|
26
|
+
|
|
27
|
+
## 0.4.0-next.0
|
|
28
|
+
|
|
29
|
+
### Minor Changes
|
|
30
|
+
|
|
31
|
+
- b768259244: **BREAKING**: Wrap batched requests and responses to /authorize in an envelope object. The latest version of the PermissionClient in @backstage/permission-common uses the new format - as long as the permission-backend is consumed using this client, no other changes are necessary.
|
|
32
|
+
|
|
33
|
+
### Patch Changes
|
|
34
|
+
|
|
35
|
+
- Updated dependencies
|
|
36
|
+
- @backstage/plugin-auth-backend@0.7.0-next.0
|
|
37
|
+
- @backstage/plugin-permission-common@0.4.0-next.0
|
|
38
|
+
- @backstage/backend-common@0.10.4-next.0
|
|
39
|
+
- @backstage/config@0.1.13-next.0
|
|
40
|
+
- @backstage/plugin-permission-node@0.4.0-next.0
|
|
41
|
+
|
|
42
|
+
## 0.3.0
|
|
43
|
+
|
|
44
|
+
### Minor Changes
|
|
45
|
+
|
|
46
|
+
- 419ca637c0: Optimizations to the integration between the permission backend and plugin-backends using createPermissionIntegrationRouter:
|
|
47
|
+
|
|
48
|
+
- The permission backend already supported batched requests to authorize, but would make calls to plugin backend to apply conditions serially. Now, after applying the policy for each authorization request, the permission backend makes a single batched /apply-conditions request to each plugin backend referenced in policy decisions.
|
|
49
|
+
- The `getResource` method accepted by `createPermissionIntegrationRouter` has been replaced with `getResources`, to allow consumers to make batch requests to upstream data stores. When /apply-conditions is called with a batch of requests, all required resources are requested in a single invocation of `getResources`.
|
|
50
|
+
|
|
51
|
+
Plugin owners consuming `createPermissionIntegrationRouter` should replace the `getResource` method in the options with a `getResources` method, accepting an array of resourceRefs, and returning an array of the corresponding resources.
|
|
52
|
+
|
|
53
|
+
### Patch Changes
|
|
54
|
+
|
|
55
|
+
- Updated dependencies
|
|
56
|
+
- @backstage/config@0.1.12
|
|
57
|
+
- @backstage/backend-common@0.10.3
|
|
58
|
+
- @backstage/plugin-permission-node@0.3.0
|
|
59
|
+
- @backstage/plugin-auth-backend@0.6.2
|
|
60
|
+
- @backstage/errors@0.2.0
|
|
61
|
+
- @backstage/plugin-permission-common@0.3.1
|
|
62
|
+
|
|
3
63
|
## 0.2.3
|
|
4
64
|
|
|
5
65
|
### Patch Changes
|
package/dist/index.cjs.js
CHANGED
|
@@ -6,38 +6,42 @@ var zod = require('zod');
|
|
|
6
6
|
var express = require('express');
|
|
7
7
|
var Router = require('express-promise-router');
|
|
8
8
|
var backendCommon = require('@backstage/backend-common');
|
|
9
|
+
var errors = require('@backstage/errors');
|
|
9
10
|
var pluginAuthBackend = require('@backstage/plugin-auth-backend');
|
|
10
11
|
var pluginPermissionCommon = require('@backstage/plugin-permission-common');
|
|
11
12
|
var fetch = require('node-fetch');
|
|
13
|
+
var lodash = require('lodash');
|
|
14
|
+
var DataLoader = require('dataloader');
|
|
12
15
|
|
|
13
16
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
14
17
|
|
|
15
18
|
var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
|
|
16
19
|
var Router__default = /*#__PURE__*/_interopDefaultLegacy(Router);
|
|
17
20
|
var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
|
|
21
|
+
var DataLoader__default = /*#__PURE__*/_interopDefaultLegacy(DataLoader);
|
|
18
22
|
|
|
19
23
|
const responseSchema = zod.z.object({
|
|
20
|
-
|
|
24
|
+
items: zod.z.array(zod.z.object({
|
|
25
|
+
id: zod.z.string(),
|
|
26
|
+
result: zod.z.literal(pluginPermissionCommon.AuthorizeResult.ALLOW).or(zod.z.literal(pluginPermissionCommon.AuthorizeResult.DENY))
|
|
27
|
+
}))
|
|
21
28
|
});
|
|
22
29
|
class PermissionIntegrationClient {
|
|
23
30
|
constructor(options) {
|
|
24
31
|
this.discovery = options.discovery;
|
|
25
32
|
}
|
|
26
|
-
async applyConditions({
|
|
27
|
-
pluginId,
|
|
28
|
-
resourceRef,
|
|
29
|
-
resourceType,
|
|
30
|
-
conditions
|
|
31
|
-
}, authHeader) {
|
|
33
|
+
async applyConditions(pluginId, decisions, authHeader) {
|
|
32
34
|
const endpoint = `${await this.discovery.getBaseUrl(pluginId)}/.well-known/backstage/permissions/apply-conditions`;
|
|
33
|
-
const request = {
|
|
34
|
-
resourceRef,
|
|
35
|
-
resourceType,
|
|
36
|
-
conditions
|
|
37
|
-
};
|
|
38
35
|
const response = await fetch__default["default"](endpoint, {
|
|
39
36
|
method: "POST",
|
|
40
|
-
body: JSON.stringify(
|
|
37
|
+
body: JSON.stringify({
|
|
38
|
+
items: decisions.map(({ id, resourceRef, resourceType, conditions }) => ({
|
|
39
|
+
id,
|
|
40
|
+
resourceRef,
|
|
41
|
+
resourceType,
|
|
42
|
+
conditions
|
|
43
|
+
}))
|
|
44
|
+
}),
|
|
41
45
|
headers: {
|
|
42
46
|
...authHeader ? { authorization: authHeader } : {},
|
|
43
47
|
"content-type": "application/json"
|
|
@@ -46,11 +50,12 @@ class PermissionIntegrationClient {
|
|
|
46
50
|
if (!response.ok) {
|
|
47
51
|
throw new Error(`Unexpected response from plugin upstream when applying conditions. Expected 200 but got ${response.status} - ${response.statusText}`);
|
|
48
52
|
}
|
|
49
|
-
|
|
53
|
+
const result = responseSchema.parse(await response.json());
|
|
54
|
+
return result.items;
|
|
50
55
|
}
|
|
51
56
|
}
|
|
52
57
|
|
|
53
|
-
const
|
|
58
|
+
const querySchema = zod.z.object({
|
|
54
59
|
id: zod.z.string(),
|
|
55
60
|
resourceRef: zod.z.string().optional(),
|
|
56
61
|
permission: zod.z.object({
|
|
@@ -65,31 +70,36 @@ const requestSchema = zod.z.array(zod.z.object({
|
|
|
65
70
|
]).optional()
|
|
66
71
|
})
|
|
67
72
|
})
|
|
68
|
-
})
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
+
});
|
|
74
|
+
const requestSchema = zod.z.object({
|
|
75
|
+
items: zod.z.array(querySchema)
|
|
76
|
+
});
|
|
77
|
+
const handleRequest = async (requests, user, policy, permissionIntegrationClient, authHeader) => {
|
|
78
|
+
const applyConditionsLoaderFor = lodash.memoize((pluginId) => {
|
|
79
|
+
return new DataLoader__default["default"]((batch) => permissionIntegrationClient.applyConditions(pluginId, batch, authHeader));
|
|
80
|
+
});
|
|
81
|
+
return Promise.all(requests.map(({ id, resourceRef, ...request }) => policy.handle(request, user).then((decision) => {
|
|
82
|
+
if (decision.result !== pluginPermissionCommon.AuthorizeResult.CONDITIONAL) {
|
|
83
|
+
return {
|
|
84
|
+
id,
|
|
85
|
+
...decision
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
if (decision.resourceType !== request.permission.resourceType) {
|
|
73
89
|
throw new Error(`Invalid resource conditions returned from permission policy for permission ${request.permission.name}`);
|
|
74
90
|
}
|
|
75
|
-
if (resourceRef) {
|
|
91
|
+
if (!resourceRef) {
|
|
76
92
|
return {
|
|
77
93
|
id,
|
|
78
|
-
...
|
|
79
|
-
resourceRef,
|
|
80
|
-
pluginId: response.pluginId,
|
|
81
|
-
resourceType: response.resourceType,
|
|
82
|
-
conditions: response.conditions
|
|
83
|
-
}, authHeader)
|
|
94
|
+
...decision
|
|
84
95
|
};
|
|
85
96
|
}
|
|
86
|
-
return {
|
|
97
|
+
return applyConditionsLoaderFor(decision.pluginId).load({
|
|
87
98
|
id,
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
return { id, ...response };
|
|
99
|
+
resourceRef,
|
|
100
|
+
...decision
|
|
101
|
+
});
|
|
102
|
+
})));
|
|
93
103
|
};
|
|
94
104
|
async function createRouter(options) {
|
|
95
105
|
const { policy, discovery, identity } = options;
|
|
@@ -104,8 +114,14 @@ async function createRouter(options) {
|
|
|
104
114
|
router.post("/authorize", async (req, res) => {
|
|
105
115
|
const token = pluginAuthBackend.IdentityClient.getBearerToken(req.header("authorization"));
|
|
106
116
|
const user = token ? await identity.authenticate(token) : void 0;
|
|
107
|
-
const
|
|
108
|
-
|
|
117
|
+
const parseResult = requestSchema.safeParse(req.body);
|
|
118
|
+
if (!parseResult.success) {
|
|
119
|
+
throw new errors.InputError(parseResult.error.toString());
|
|
120
|
+
}
|
|
121
|
+
const body = parseResult.data;
|
|
122
|
+
res.json({
|
|
123
|
+
items: await handleRequest(body.items, user, policy, permissionIntegrationClient, req.header("authorization"))
|
|
124
|
+
});
|
|
109
125
|
});
|
|
110
126
|
router.use(backendCommon.errorHandler());
|
|
111
127
|
return router;
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/service/PermissionIntegrationClient.ts","../src/service/router.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 fetch from 'node-fetch';\nimport { z } from 'zod';\nimport { PluginEndpointDiscovery } from '@backstage/backend-common';\nimport {\n AuthorizeResult,\n PermissionCondition,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequest,\n ApplyConditionsResponse,\n} from '@backstage/plugin-permission-node';\n\nconst responseSchema = z.object({\n result: z.literal(AuthorizeResult.ALLOW).or(z.literal(AuthorizeResult.DENY)),\n});\n\nexport class PermissionIntegrationClient {\n private readonly discovery: PluginEndpointDiscovery;\n\n constructor(options: { discovery: PluginEndpointDiscovery }) {\n this.discovery = options.discovery;\n }\n\n async applyConditions(\n {\n pluginId,\n resourceRef,\n resourceType,\n conditions,\n }: {\n resourceRef: string;\n pluginId: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n },\n authHeader?: string,\n ): Promise<ApplyConditionsResponse> {\n const endpoint = `${await this.discovery.getBaseUrl(\n pluginId,\n )}/.well-known/backstage/permissions/apply-conditions`;\n\n const request: ApplyConditionsRequest = {\n resourceRef,\n resourceType,\n conditions,\n };\n\n const response = await fetch(endpoint, {\n method: 'POST',\n body: JSON.stringify(request),\n headers: {\n ...(authHeader ? { authorization: authHeader } : {}),\n 'content-type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Unexpected response from plugin upstream when applying conditions. Expected 200 but got ${response.status} - ${response.statusText}`,\n );\n }\n\n return responseSchema.parse(await response.json());\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 { z } from 'zod';\nimport express, { Request, Response } from 'express';\nimport Router from 'express-promise-router';\nimport { Logger } from 'winston';\nimport {\n errorHandler,\n PluginEndpointDiscovery,\n} from '@backstage/backend-common';\nimport {\n BackstageIdentityResponse,\n IdentityClient,\n} from '@backstage/plugin-auth-backend';\nimport {\n AuthorizeResult,\n AuthorizeResponse,\n AuthorizeRequest,\n Identified,\n} from '@backstage/plugin-permission-common';\nimport { PermissionPolicy } from '@backstage/plugin-permission-node';\nimport { PermissionIntegrationClient } from './PermissionIntegrationClient';\n\nconst requestSchema: z.ZodSchema<Identified<AuthorizeRequest>[]> = z.array(\n z.object({\n id: z.string(),\n resourceRef: z.string().optional(),\n permission: z.object({\n name: z.string(),\n resourceType: z.string().optional(),\n attributes: z.object({\n action: z\n .union([\n z.literal('create'),\n z.literal('read'),\n z.literal('update'),\n z.literal('delete'),\n ])\n .optional(),\n }),\n }),\n }),\n);\n\n/**\n * Options required when constructing a new {@link express#Router} using\n * {@link createRouter}.\n *\n * @public\n */\nexport interface RouterOptions {\n logger: Logger;\n discovery: PluginEndpointDiscovery;\n policy: PermissionPolicy;\n identity: IdentityClient;\n}\n\nconst handleRequest = async (\n { id, resourceRef, ...request }: Identified<AuthorizeRequest>,\n user: BackstageIdentityResponse | undefined,\n policy: PermissionPolicy,\n permissionIntegrationClient: PermissionIntegrationClient,\n authHeader?: string,\n): Promise<Identified<AuthorizeResponse>> => {\n const response = await policy.handle(request, user);\n\n if (response.result === AuthorizeResult.CONDITIONAL) {\n // Sanity check that any resource provided matches the one expected by the permission\n if (request.permission.resourceType !== response.resourceType) {\n throw new Error(\n `Invalid resource conditions returned from permission policy for permission ${request.permission.name}`,\n );\n }\n\n if (resourceRef) {\n return {\n id,\n ...(await permissionIntegrationClient.applyConditions(\n {\n resourceRef,\n pluginId: response.pluginId,\n resourceType: response.resourceType,\n conditions: response.conditions,\n },\n authHeader,\n )),\n };\n }\n\n return {\n id,\n result: AuthorizeResult.CONDITIONAL,\n conditions: response.conditions,\n };\n }\n\n return { id, ...response };\n};\n\n/**\n * Creates a new {@link express#Router} which provides the backend API\n * for the permission system.\n *\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { policy, discovery, identity } = options;\n\n const permissionIntegrationClient = new PermissionIntegrationClient({\n discovery,\n });\n\n const router = Router();\n router.use(express.json());\n\n router.get('/health', (_, response) => {\n response.send({ status: 'ok' });\n });\n\n router.post(\n '/authorize',\n async (\n req: Request<Identified<AuthorizeRequest>[]>,\n res: Response<Identified<AuthorizeResponse>[]>,\n ) => {\n const token = IdentityClient.getBearerToken(req.header('authorization'));\n const user = token ? await identity.authenticate(token) : undefined;\n\n const body = requestSchema.parse(req.body);\n\n res.json(\n await Promise.all(\n body.map(request =>\n handleRequest(\n request,\n user,\n policy,\n permissionIntegrationClient,\n req.header('authorization'),\n ),\n ),\n ),\n );\n },\n );\n\n router.use(errorHandler());\n return router;\n}\n"],"names":["z","AuthorizeResult","fetch","Router","express","IdentityClient","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,MAAM,iBAAiBA,MAAE,OAAO;AAAA,EAC9B,QAAQA,MAAE,QAAQC,uCAAgB,OAAO,GAAGD,MAAE,QAAQC,uCAAgB;AAAA;kCAG/B;AAAA,EAGvC,YAAY,SAAiD;AAC3D,SAAK,YAAY,QAAQ;AAAA;AAAA,QAGrB,gBACJ;AAAA,IACE;AAAA,IACA;AA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,UACvB,YAAY,SAAS;AAAA,WAEvB;AAAA;AAAA;AAKN,WAAO;AAAA,MACL;AAAA,MACA,QAAQA,uCAAgB;AAAA,MACxB,YAAY,SAAS;AAAA;AAAA;AAIzB,SAAO,EAAE,OAAO;AAAA;4BAUhB,SACyB;AACzB,QAAM,EAAE,QAAQ,WAAW,aAAa;AAExC,QAAM,8BAA8B,IAAI,4BAA4B;AAAA,IAClE;AAAA;AAGF,QAAM,SAASE;AACf,SAAO,IAAIC,4BAAQ;AAEnB,SAAO,IAAI,WAAW,CAAC,GAAG,aAAa;AACrC,aAAS,KAAK,EAAE,QAAQ;AAAA;AAG1B,SAAO,KACL,cACA,OACE,KACA,QACG;AACH,UAAM,QAAQC,iCAAe,eAAe,IAAI,OAAO;AACvD,UAAM,OAAO,QAAQ,MAAM,SAAS,aAAa,SAAS;AAE1D,UAAM,OAAO,cAAc,MAAM,IAAI;AAErC,QAAI,KACF,MAAM,QAAQ,IACZ,KAAK,IAAI,aACP,cACE,SACA,MACA,QACA,6BACA,IAAI,OAAO;AAAA;AAQvB,SAAO,IAAIC;AACX,SAAO;AAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/service/PermissionIntegrationClient.ts","../src/service/router.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 fetch from 'node-fetch';\nimport { z } from 'zod';\nimport { PluginEndpointDiscovery } from '@backstage/backend-common';\nimport { AuthorizeResult } from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n ConditionalPolicyDecision,\n} from '@backstage/plugin-permission-node';\n\nconst responseSchema = z.object({\n items: z.array(\n z.object({\n id: z.string(),\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n }),\n ),\n});\n\nexport type ResourcePolicyDecision = ConditionalPolicyDecision & {\n resourceRef: string;\n};\n\nexport class PermissionIntegrationClient {\n private readonly discovery: PluginEndpointDiscovery;\n\n constructor(options: { discovery: PluginEndpointDiscovery }) {\n this.discovery = options.discovery;\n }\n\n async applyConditions(\n pluginId: string,\n decisions: readonly ApplyConditionsRequestEntry[],\n authHeader?: string,\n ): Promise<ApplyConditionsResponseEntry[]> {\n const endpoint = `${await this.discovery.getBaseUrl(\n pluginId,\n )}/.well-known/backstage/permissions/apply-conditions`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n body: JSON.stringify({\n items: decisions.map(\n ({ id, resourceRef, resourceType, conditions }) => ({\n id,\n resourceRef,\n resourceType,\n conditions,\n }),\n ),\n }),\n headers: {\n ...(authHeader ? { authorization: authHeader } : {}),\n 'content-type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Unexpected response from plugin upstream when applying conditions. Expected 200 but got ${response.status} - ${response.statusText}`,\n );\n }\n\n const result = responseSchema.parse(await response.json());\n\n return result.items;\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 { z } from 'zod';\nimport express, { Request, Response } from 'express';\nimport Router from 'express-promise-router';\nimport { Logger } from 'winston';\nimport {\n errorHandler,\n PluginEndpointDiscovery,\n} from '@backstage/backend-common';\nimport { InputError } from '@backstage/errors';\nimport {\n BackstageIdentityResponse,\n IdentityClient,\n} from '@backstage/plugin-auth-backend';\nimport {\n AuthorizeResult,\n AuthorizeDecision,\n AuthorizeQuery,\n Identified,\n AuthorizeRequest,\n AuthorizeResponse,\n} from '@backstage/plugin-permission-common';\nimport {\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry,\n PermissionPolicy,\n} from '@backstage/plugin-permission-node';\nimport { PermissionIntegrationClient } from './PermissionIntegrationClient';\nimport { memoize } from 'lodash';\nimport DataLoader from 'dataloader';\n\nconst querySchema: z.ZodSchema<Identified<AuthorizeQuery>> = z.object({\n id: z.string(),\n resourceRef: z.string().optional(),\n permission: z.object({\n name: z.string(),\n resourceType: z.string().optional(),\n attributes: z.object({\n action: z\n .union([\n z.literal('create'),\n z.literal('read'),\n z.literal('update'),\n z.literal('delete'),\n ])\n .optional(),\n }),\n }),\n});\n\nconst requestSchema: z.ZodSchema<AuthorizeRequest> = z.object({\n items: z.array(querySchema),\n});\n\n/**\n * Options required when constructing a new {@link express#Router} using\n * {@link createRouter}.\n *\n * @public\n */\nexport interface RouterOptions {\n logger: Logger;\n discovery: PluginEndpointDiscovery;\n policy: PermissionPolicy;\n identity: IdentityClient;\n}\n\nconst handleRequest = async (\n requests: Identified<AuthorizeQuery>[],\n user: BackstageIdentityResponse | undefined,\n policy: PermissionPolicy,\n permissionIntegrationClient: PermissionIntegrationClient,\n authHeader?: string,\n): Promise<Identified<AuthorizeDecision>[]> => {\n const applyConditionsLoaderFor = memoize((pluginId: string) => {\n return new DataLoader<\n ApplyConditionsRequestEntry,\n ApplyConditionsResponseEntry\n >(batch =>\n permissionIntegrationClient.applyConditions(pluginId, batch, authHeader),\n );\n });\n\n return Promise.all(\n requests.map(({ id, resourceRef, ...request }) =>\n policy.handle(request, user).then(decision => {\n if (decision.result !== AuthorizeResult.CONDITIONAL) {\n return {\n id,\n ...decision,\n };\n }\n\n if (decision.resourceType !== request.permission.resourceType) {\n throw new Error(\n `Invalid resource conditions returned from permission policy for permission ${request.permission.name}`,\n );\n }\n\n if (!resourceRef) {\n return {\n id,\n ...decision,\n };\n }\n\n return applyConditionsLoaderFor(decision.pluginId).load({\n id,\n resourceRef,\n ...decision,\n });\n }),\n ),\n );\n};\n\n/**\n * Creates a new {@link express#Router} which provides the backend API\n * for the permission system.\n *\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { policy, discovery, identity } = options;\n\n const permissionIntegrationClient = new PermissionIntegrationClient({\n discovery,\n });\n\n const router = Router();\n router.use(express.json());\n\n router.get('/health', (_, response) => {\n response.send({ status: 'ok' });\n });\n\n router.post(\n '/authorize',\n async (\n req: Request<AuthorizeRequest>,\n res: Response<AuthorizeResponse>,\n ) => {\n const token = IdentityClient.getBearerToken(req.header('authorization'));\n const user = token ? await identity.authenticate(token) : undefined;\n\n const parseResult = requestSchema.safeParse(req.body);\n\n if (!parseResult.success) {\n throw new InputError(parseResult.error.toString());\n }\n\n const body = parseResult.data;\n\n res.json({\n items: await handleRequest(\n body.items,\n user,\n policy,\n permissionIntegrationClient,\n req.header('authorization'),\n ),\n });\n },\n );\n\n router.use(errorHandler());\n\n return router;\n}\n"],"names":["z","AuthorizeResult","fetch","memoize","DataLoader","Router","express","IdentityClient","InputError","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,iBAAiBA,MAAE,OAAO;AAAA,EAC9B,OAAOA,MAAE,MACPA,MAAE,OAAO;AAAA,IACP,IAAIA,MAAE;AAAA,IACN,QAAQA,MACL,QAAQC,uCAAgB,OACxB,GAAGD,MAAE,QAAQC,uCAAgB;AAAA;AAAA;kCASG;AAAA,EAGvC,YAAY,SAAiD;AAC3D,SAAK,YAAY,QAAQ;AAAA;AAAA,QAGrB,gBACJ,UACA,WACA,YACyC;AACzC,UAAM,WAAW,GAAG,MAAM,KAAK,UAAU,WACvC;AAGF,UAAM,WAAW,MAAMC,0BAAM,UAAU;AAAA,MACr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AQ,WAAW,cAAc;AAC7D,YAAM,IAAI,MACR,8EAA8E,QAAQ,WAAW;AAAA;AAIrG,QAAI,CAAC,aAAa;AAChB,aAAO;AAAA,QACL;AAAA,WACG;AAAA;AAAA;AAIP,WAAO,yBAAyB,SAAS,UAAU,KAAK;AAAA,MACtD;AAAA,MACA;AAAA,SACG;AAAA;AAAA;AAAA;4BAcX,SACyB;AACzB,QAAM,EAAE,QAAQ,WAAW,aAAa;AAExC,QAAM,8BAA8B,IAAI,4BAA4B;AAAA,IAClE;AAAA;AAGF,QAAM,SAASI;AACf,SAAO,IAAIC,4BAAQ;AAEnB,SAAO,IAAI,WAAW,CAAC,GAAG,aAAa;AACrC,aAAS,KAAK,EAAE,QAAQ;AAAA;AAG1B,SAAO,KACL,cACA,OACE,KACA,QACG;AACH,UAAM,QAAQC,iCAAe,eAAe,IAAI,OAAO;AACvD,UAAM,OAAO,QAAQ,MAAM,SAAS,aAAa,SAAS;AAE1D,UAAM,cAAc,cAAc,UAAU,IAAI;AAEhD,QAAI,CAAC,YAAY,SAAS;AACxB,YAAM,IAAIC,kBAAW,YAAY,MAAM;AAAA;AAGzC,UAAM,OAAO,YAAY;AAEzB,QAAI,KAAK;AAAA,MACP,OAAO,MAAM,cACX,KAAK,OACL,MACA,QACA,6BACA,IAAI,OAAO;AAAA;AAAA;AAMnB,SAAO,IAAIC;AAEX,SAAO;AAAA;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-permission-backend",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"main": "dist/index.cjs.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -19,21 +19,25 @@
|
|
|
19
19
|
"clean": "backstage-cli clean"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@backstage/backend-common": "^0.10.
|
|
23
|
-
"@backstage/config": "^0.1.
|
|
24
|
-
"@backstage/
|
|
25
|
-
"@backstage/plugin-
|
|
26
|
-
"@backstage/plugin-permission-
|
|
22
|
+
"@backstage/backend-common": "^0.10.5",
|
|
23
|
+
"@backstage/config": "^0.1.13",
|
|
24
|
+
"@backstage/errors": "^0.2.0",
|
|
25
|
+
"@backstage/plugin-auth-backend": "^0.8.0",
|
|
26
|
+
"@backstage/plugin-permission-common": "^0.4.0",
|
|
27
|
+
"@backstage/plugin-permission-node": "^0.4.1",
|
|
27
28
|
"@types/express": "*",
|
|
29
|
+
"dataloader": "^2.0.0",
|
|
28
30
|
"express": "^4.17.1",
|
|
29
31
|
"express-promise-router": "^4.1.0",
|
|
32
|
+
"lodash": "^4.17.21",
|
|
30
33
|
"node-fetch": "^2.6.1",
|
|
31
34
|
"winston": "^3.2.1",
|
|
32
35
|
"yn": "^4.0.0",
|
|
33
36
|
"zod": "^3.11.6"
|
|
34
37
|
},
|
|
35
38
|
"devDependencies": {
|
|
36
|
-
"@backstage/cli": "^0.
|
|
39
|
+
"@backstage/cli": "^0.13.0",
|
|
40
|
+
"@types/lodash": "^4.14.151",
|
|
37
41
|
"@types/supertest": "^2.0.8",
|
|
38
42
|
"msw": "^0.35.0",
|
|
39
43
|
"supertest": "^6.1.6"
|
|
@@ -41,5 +45,5 @@
|
|
|
41
45
|
"files": [
|
|
42
46
|
"dist"
|
|
43
47
|
],
|
|
44
|
-
"gitHead": "
|
|
48
|
+
"gitHead": "493394603a2c47ea1d141159af9bc7bb84fac9e5"
|
|
45
49
|
}
|