@backstage/plugin-permission-common 0.5.3 → 0.6.0
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 +61 -0
- package/dist/index.cjs.js +73 -18
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +205 -50
- package/dist/index.esm.js +70 -19
- package/dist/index.esm.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,66 @@
|
|
|
1
1
|
# @backstage/plugin-permission-common
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 8012ac46a0: Add `resourceType` property to `PermissionCondition` type to allow matching them with `ResourcePermission` instances.
|
|
8
|
+
- c98d271466: Refactor api types into more specific, decoupled names.
|
|
9
|
+
|
|
10
|
+
- **BREAKING:**
|
|
11
|
+
- Renamed `AuthorizeDecision` to `EvaluatePermissionResponse`
|
|
12
|
+
- Renamed `AuthorizeQuery` to `EvaluatePermissionRequest`
|
|
13
|
+
- Renamed `AuthorizeRequest` to `EvaluatePermissionRequestBatch`
|
|
14
|
+
- Renamed `AuthorizeResponse` to `EvaluatePermissionResponseBatch`
|
|
15
|
+
- Renamed `Identified` to `IdentifiedPermissionMessage`
|
|
16
|
+
- Add `PermissionMessageBatch` helper type
|
|
17
|
+
- Add `ConditionalPolicyDecision`, `DefinitivePolicyDecision`, and `PolicyDecision` types from `@backstage/plugin-permission-node`
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- 90754d4fa9: Removed [strict](https://github.com/colinhacks/zod#strict) validation from `PermissionCriteria` schemas to support backward-compatible changes.
|
|
22
|
+
- 2b07063d77: Added `PermissionEvaluator`, which will replace the existing `PermissionAuthorizer` interface. This new interface provides stronger type safety and validation by splitting `PermissionAuthorizer.authorize()` into two methods:
|
|
23
|
+
|
|
24
|
+
- `authorize()`: Used when the caller requires a definitive decision.
|
|
25
|
+
- `authorizeConditional()`: Used when the caller can optimize the evaluation of any conditional decisions. For example, a plugin backend may want to use conditions in a database query instead of evaluating each resource in memory.
|
|
26
|
+
|
|
27
|
+
- 8012ac46a0: Add `isPermission` helper method.
|
|
28
|
+
- 95284162d6: - Add more specific `Permission` types.
|
|
29
|
+
- Add `createPermission` helper to infer the appropriate type for some permission input.
|
|
30
|
+
- Add `isResourcePermission` helper to refine Permissions to ResourcePermissions.
|
|
31
|
+
|
|
32
|
+
## 0.6.0-next.1
|
|
33
|
+
|
|
34
|
+
### Patch Changes
|
|
35
|
+
|
|
36
|
+
- 2b07063d77: Added `PermissionEvaluator`, which will replace the existing `PermissionAuthorizer` interface. This new interface provides stronger type safety and validation by splitting `PermissionAuthorizer.authorize()` into two methods:
|
|
37
|
+
|
|
38
|
+
- `authorize()`: Used when the caller requires a definitive decision.
|
|
39
|
+
- `authorizeConditional()`: Used when the caller can optimize the evaluation of any conditional decisions. For example, a plugin backend may want to use conditions in a database query instead of evaluating each resource in memory.
|
|
40
|
+
|
|
41
|
+
## 0.6.0-next.0
|
|
42
|
+
|
|
43
|
+
### Minor Changes
|
|
44
|
+
|
|
45
|
+
- 8012ac46a0: Add `resourceType` property to `PermissionCondition` type to allow matching them with `ResourcePermission` instances.
|
|
46
|
+
- c98d271466: Refactor api types into more specific, decoupled names.
|
|
47
|
+
|
|
48
|
+
- **BREAKING:**
|
|
49
|
+
- Renamed `AuthorizeDecision` to `EvaluatePermissionResponse`
|
|
50
|
+
- Renamed `AuthorizeQuery` to `EvaluatePermissionRequest`
|
|
51
|
+
- Renamed `AuthorizeRequest` to `EvaluatePermissionRequestBatch`
|
|
52
|
+
- Renamed `AuthorizeResponse` to `EvaluatePermissionResponseBatch`
|
|
53
|
+
- Renamed `Identified` to `IdentifiedPermissionMessage`
|
|
54
|
+
- Add `PermissionMessageBatch` helper type
|
|
55
|
+
- Add `ConditionalPolicyDecision`, `DefinitivePolicyDecision`, and `PolicyDecision` types from `@backstage/plugin-permission-node`
|
|
56
|
+
|
|
57
|
+
### Patch Changes
|
|
58
|
+
|
|
59
|
+
- 8012ac46a0: Add `isPermission` helper method.
|
|
60
|
+
- 95284162d6: - Add more specific `Permission` types.
|
|
61
|
+
- Add `createPermission` helper to infer the appropriate type for some permission input.
|
|
62
|
+
- Add `isResourcePermission` helper to refine Permissions to ResourcePermissions.
|
|
63
|
+
|
|
3
64
|
## 0.5.3
|
|
4
65
|
|
|
5
66
|
### Patch Changes
|
package/dist/index.cjs.js
CHANGED
|
@@ -37,6 +37,15 @@ var AuthorizeResult = /* @__PURE__ */ ((AuthorizeResult2) => {
|
|
|
37
37
|
return AuthorizeResult2;
|
|
38
38
|
})(AuthorizeResult || {});
|
|
39
39
|
|
|
40
|
+
function isPermission(permission, comparedPermission) {
|
|
41
|
+
return permission.name === comparedPermission.name;
|
|
42
|
+
}
|
|
43
|
+
function isResourcePermission(permission, resourceType) {
|
|
44
|
+
if (!("resourceType" in permission)) {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
return !resourceType || permission.resourceType === resourceType;
|
|
48
|
+
}
|
|
40
49
|
function isCreatePermission(permission) {
|
|
41
50
|
return permission.attributes.action === "create";
|
|
42
51
|
}
|
|
@@ -49,20 +58,64 @@ function isUpdatePermission(permission) {
|
|
|
49
58
|
function isDeletePermission(permission) {
|
|
50
59
|
return permission.attributes.action === "delete";
|
|
51
60
|
}
|
|
61
|
+
function toPermissionEvaluator(permissionAuthorizer) {
|
|
62
|
+
return {
|
|
63
|
+
authorize: async (requests, options) => {
|
|
64
|
+
const response = await permissionAuthorizer.authorize(requests, options);
|
|
65
|
+
return response;
|
|
66
|
+
},
|
|
67
|
+
authorizeConditional(requests, options) {
|
|
68
|
+
const parsedRequests = requests;
|
|
69
|
+
return permissionAuthorizer.authorize(parsedRequests, options);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function createPermission({
|
|
75
|
+
name,
|
|
76
|
+
attributes,
|
|
77
|
+
resourceType
|
|
78
|
+
}) {
|
|
79
|
+
if (resourceType) {
|
|
80
|
+
return {
|
|
81
|
+
type: "resource",
|
|
82
|
+
name,
|
|
83
|
+
attributes,
|
|
84
|
+
resourceType
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
type: "basic",
|
|
89
|
+
name,
|
|
90
|
+
attributes
|
|
91
|
+
};
|
|
92
|
+
}
|
|
52
93
|
|
|
53
94
|
const permissionCriteriaSchema = zod.z.lazy(() => zod.z.object({
|
|
54
95
|
rule: zod.z.string(),
|
|
96
|
+
resourceType: zod.z.string(),
|
|
55
97
|
params: zod.z.array(zod.z.unknown())
|
|
56
|
-
}).
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
98
|
+
}).or(zod.z.object({ anyOf: zod.z.array(permissionCriteriaSchema).nonempty() })).or(zod.z.object({ allOf: zod.z.array(permissionCriteriaSchema).nonempty() })).or(zod.z.object({ not: permissionCriteriaSchema })));
|
|
99
|
+
const authorizePermissionResponseSchema = zod.z.object({
|
|
100
|
+
result: zod.z.literal(AuthorizeResult.ALLOW).or(zod.z.literal(AuthorizeResult.DENY))
|
|
101
|
+
});
|
|
102
|
+
const queryPermissionResponseSchema = zod.z.union([
|
|
103
|
+
zod.z.object({
|
|
60
104
|
result: zod.z.literal(AuthorizeResult.ALLOW).or(zod.z.literal(AuthorizeResult.DENY))
|
|
61
|
-
})
|
|
62
|
-
|
|
105
|
+
}),
|
|
106
|
+
zod.z.object({
|
|
63
107
|
result: zod.z.literal(AuthorizeResult.CONDITIONAL),
|
|
108
|
+
pluginId: zod.z.string(),
|
|
109
|
+
resourceType: zod.z.string(),
|
|
64
110
|
conditions: permissionCriteriaSchema
|
|
65
|
-
})
|
|
111
|
+
})
|
|
112
|
+
]);
|
|
113
|
+
const responseSchema = (itemSchema, ids) => zod.z.object({
|
|
114
|
+
items: zod.z.array(zod.z.intersection(zod.z.object({
|
|
115
|
+
id: zod.z.string()
|
|
116
|
+
}), itemSchema)).refine((items) => items.length === ids.size && items.every(({ id }) => ids.has(id)), {
|
|
117
|
+
message: "Items in response do not match request"
|
|
118
|
+
})
|
|
66
119
|
});
|
|
67
120
|
class PermissionClient {
|
|
68
121
|
constructor(options) {
|
|
@@ -70,7 +123,13 @@ class PermissionClient {
|
|
|
70
123
|
this.discovery = options.discovery;
|
|
71
124
|
this.enabled = (_a = options.config.getOptionalBoolean("permission.enabled")) != null ? _a : false;
|
|
72
125
|
}
|
|
73
|
-
async authorize(
|
|
126
|
+
async authorize(requests, options) {
|
|
127
|
+
return this.makeRequest(requests, authorizePermissionResponseSchema, options);
|
|
128
|
+
}
|
|
129
|
+
async authorizeConditional(queries, options) {
|
|
130
|
+
return this.makeRequest(queries, queryPermissionResponseSchema, options);
|
|
131
|
+
}
|
|
132
|
+
async makeRequest(queries, itemSchema, options) {
|
|
74
133
|
if (!this.enabled) {
|
|
75
134
|
return queries.map((_) => ({ result: AuthorizeResult.ALLOW }));
|
|
76
135
|
}
|
|
@@ -93,8 +152,8 @@ class PermissionClient {
|
|
|
93
152
|
throw await errors.ResponseError.fromResponse(response);
|
|
94
153
|
}
|
|
95
154
|
const responseBody = await response.json();
|
|
96
|
-
|
|
97
|
-
const responsesById =
|
|
155
|
+
const parsedResponse = responseSchema(itemSchema, new Set(request.items.map(({ id }) => id))).parse(responseBody);
|
|
156
|
+
const responsesById = parsedResponse.items.reduce((acc, r) => {
|
|
98
157
|
acc[r.id] = r;
|
|
99
158
|
return acc;
|
|
100
159
|
}, {});
|
|
@@ -103,20 +162,16 @@ class PermissionClient {
|
|
|
103
162
|
getAuthorizationHeader(token) {
|
|
104
163
|
return token ? { Authorization: `Bearer ${token}` } : {};
|
|
105
164
|
}
|
|
106
|
-
assertValidResponse(request, json) {
|
|
107
|
-
const authorizedResponses = responseSchema.parse(json);
|
|
108
|
-
const responseIds = authorizedResponses.items.map((r) => r.id);
|
|
109
|
-
const hasAllRequestIds = request.items.every((r) => responseIds.includes(r.id));
|
|
110
|
-
if (!hasAllRequestIds) {
|
|
111
|
-
throw new Error("Unexpected authorization response from permission-backend");
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
165
|
}
|
|
115
166
|
|
|
116
167
|
exports.AuthorizeResult = AuthorizeResult;
|
|
117
168
|
exports.PermissionClient = PermissionClient;
|
|
169
|
+
exports.createPermission = createPermission;
|
|
118
170
|
exports.isCreatePermission = isCreatePermission;
|
|
119
171
|
exports.isDeletePermission = isDeletePermission;
|
|
172
|
+
exports.isPermission = isPermission;
|
|
120
173
|
exports.isReadPermission = isReadPermission;
|
|
174
|
+
exports.isResourcePermission = isResourcePermission;
|
|
121
175
|
exports.isUpdatePermission = isUpdatePermission;
|
|
176
|
+
exports.toPermissionEvaluator = toPermissionEvaluator;
|
|
122
177
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/types/api.ts","../src/permissions/util.ts","../src/PermissionClient.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 { Permission } from './permission';\n\n/**\n * A request with a UUID identifier, so that batched responses can be matched up with the original\n * requests.\n * @public\n */\nexport type Identified<T> = T & { id: string };\n\n/**\n * The result of an authorization request.\n * @public\n */\nexport enum AuthorizeResult {\n /**\n * The authorization request is denied.\n */\n DENY = 'DENY',\n /**\n * The authorization request is allowed.\n */\n ALLOW = 'ALLOW',\n /**\n * The authorization request is allowed if the provided conditions are met.\n */\n CONDITIONAL = 'CONDITIONAL',\n}\n\n/**\n * An individual authorization request for {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeQuery = {\n permission: Permission;\n resourceRef?: string;\n};\n\n/**\n * A batch of authorization requests from {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeRequest = {\n items: Identified<AuthorizeQuery>[];\n};\n\n/**\n * A condition returned with a CONDITIONAL authorization response.\n *\n * Conditions are a reference to a rule defined by a plugin, and parameters to apply the rule. For\n * example, a rule might be `isOwner` from the catalog-backend, and params may be a list of entity\n * claims from a identity token.\n * @public\n */\nexport type PermissionCondition<TParams extends unknown[] = unknown[]> = {\n rule: string;\n params: TParams;\n};\n\n/**\n * Utility type to represent an array with 1 or more elements.\n * @ignore\n */\ntype NonEmptyArray<T> = [T, ...T[]];\n\n/**\n * Represents a logical AND for the provided criteria.\n * @public\n */\nexport type AllOfCriteria<TQuery> = {\n allOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a logical OR for the provided criteria.\n * @public\n */\nexport type AnyOfCriteria<TQuery> = {\n anyOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a negation of the provided criteria.\n * @public\n */\nexport type NotCriteria<TQuery> = {\n not: PermissionCriteria<TQuery>;\n};\n\n/**\n * Composes several {@link PermissionCondition}s as criteria with a nested AND/OR structure.\n * @public\n */\nexport type PermissionCriteria<TQuery> =\n | AllOfCriteria<TQuery>\n | AnyOfCriteria<TQuery>\n | NotCriteria<TQuery>\n | TQuery;\n\n/**\n * An individual authorization response from {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeDecision =\n | { result: AuthorizeResult.ALLOW | AuthorizeResult.DENY }\n | {\n result: AuthorizeResult.CONDITIONAL;\n conditions: PermissionCriteria<PermissionCondition>;\n };\n\n/**\n * A batch of authorization responses from {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeResponse = {\n items: Identified<AuthorizeDecision>[];\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 { Permission } from '../types';\n\n/**\n * Check if a given permission is related to a create action.\n * @public\n */\nexport function isCreatePermission(permission: Permission) {\n return permission.attributes.action === 'create';\n}\n\n/**\n * Check if a given permission is related to a read action.\n * @public\n */\nexport function isReadPermission(permission: Permission) {\n return permission.attributes.action === 'read';\n}\n\n/**\n * Check if a given permission is related to an update action.\n * @public\n */\nexport function isUpdatePermission(permission: Permission) {\n return permission.attributes.action === 'update';\n}\n\n/**\n * Check if a given permission is related to a delete action.\n * @public\n */\nexport function isDeletePermission(permission: Permission) {\n return permission.attributes.action === 'delete';\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 { Config } from '@backstage/config';\nimport { ResponseError } from '@backstage/errors';\nimport fetch from 'cross-fetch';\nimport * as uuid from 'uuid';\nimport { z } from 'zod';\nimport {\n AuthorizeResult,\n AuthorizeQuery,\n AuthorizeDecision,\n Identified,\n PermissionCriteria,\n PermissionCondition,\n AuthorizeResponse,\n AuthorizeRequest,\n} from './types/api';\nimport { DiscoveryApi } from './types/discovery';\nimport {\n PermissionAuthorizer,\n AuthorizeRequestOptions,\n} from './types/permission';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z\n .object({\n rule: z.string(),\n params: z.array(z.unknown()),\n })\n .strict()\n .or(\n z\n .object({ anyOf: z.array(permissionCriteriaSchema).nonempty() })\n .strict(),\n )\n .or(\n z\n .object({ allOf: z.array(permissionCriteriaSchema).nonempty() })\n .strict(),\n )\n .or(z.object({ not: permissionCriteriaSchema }).strict()),\n);\n\nconst responseSchema = z.object({\n items: z.array(\n z\n .object({\n id: z.string(),\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n })\n .or(\n z.object({\n id: z.string(),\n result: z.literal(AuthorizeResult.CONDITIONAL),\n conditions: permissionCriteriaSchema,\n }),\n ),\n ),\n});\n\n/**\n * An isomorphic client for requesting authorization for Backstage permissions.\n * @public\n */\nexport class PermissionClient implements PermissionAuthorizer {\n private readonly enabled: boolean;\n private readonly discovery: DiscoveryApi;\n\n constructor(options: { discovery: DiscoveryApi; config: Config }) {\n this.discovery = options.discovery;\n this.enabled =\n options.config.getOptionalBoolean('permission.enabled') ?? false;\n }\n\n /**\n * Request authorization from the permission-backend for the given set of permissions.\n *\n * Authorization requests check that a given Backstage user can perform a protected operation,\n * potentially for a specific resource (such as a catalog entity). The Backstage identity token\n * should be included in the `options` if available.\n *\n * Permissions can be imported from plugins exposing them, such as `catalogEntityReadPermission`.\n *\n * The response will be either ALLOW or DENY when either the permission has no resourceType, or a\n * resourceRef is provided in the request. For permissions with a resourceType, CONDITIONAL may be\n * returned if no resourceRef is provided in the request. Conditional responses are intended only\n * for backends which have access to the data source for permissioned resources, so that filters\n * can be applied when loading collections of resources.\n * @public\n */\n async authorize(\n queries: AuthorizeQuery[],\n options?: AuthorizeRequestOptions,\n ): Promise<AuthorizeDecision[]> {\n // TODO(permissions): it would be great to provide some kind of typing guarantee that\n // conditional responses will only ever be returned for requests containing a resourceType\n // but no resourceRef. That way clients who aren't prepared to handle filtering according\n // to conditions can be guaranteed that they won't unexpectedly get a CONDITIONAL response.\n\n if (!this.enabled) {\n return queries.map(_ => ({ result: AuthorizeResult.ALLOW }));\n }\n\n const request: AuthorizeRequest = {\n items: queries.map(query => ({\n id: uuid.v4(),\n ...query,\n })),\n };\n\n const permissionApi = await this.discovery.getBaseUrl('permission');\n const response = await fetch(`${permissionApi}/authorize`, {\n method: 'POST',\n body: JSON.stringify(request),\n headers: {\n ...this.getAuthorizationHeader(options?.token),\n 'content-type': 'application/json',\n },\n });\n if (!response.ok) {\n throw await ResponseError.fromResponse(response);\n }\n\n const responseBody = await response.json();\n this.assertValidResponse(request, responseBody);\n\n const responsesById = responseBody.items.reduce((acc, r) => {\n acc[r.id] = r;\n return acc;\n }, {} as Record<string, Identified<AuthorizeDecision>>);\n\n return request.items.map(query => responsesById[query.id]);\n }\n\n private getAuthorizationHeader(token?: string): Record<string, string> {\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n\n private assertValidResponse(\n request: AuthorizeRequest,\n json: any,\n ): asserts json is AuthorizeResponse {\n const authorizedResponses = responseSchema.parse(json);\n const responseIds = authorizedResponses.items.map(r => r.id);\n const hasAllRequestIds = request.items.every(r =>\n responseIds.includes(r.id),\n );\n if (!hasAllRequestIds) {\n throw new Error(\n 'Unexpected authorization response from permission-backend',\n );\n }\n }\n}\n"],"names":["z","uuid","fetch","ResponseError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BY,IAAA,eAAA,qBAAA,gBAAL,KAAA;AAIL,EAAO,gBAAA,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;AAIP,EAAQ,gBAAA,CAAA,OAAA,CAAA,GAAA,OAAA,CAAA;AAIR,EAAc,gBAAA,CAAA,aAAA,CAAA,GAAA,aAAA,CAAA;AAZJ,EAAA,OAAA,gBAAA,CAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;ACPL,SAAA,kBAAA,CAA4B,UAAwB,EAAA;AACz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,KAAM,CAAA,GAAA,CAAI,OAAK,CAAE,CAAA,EAAA,CAAA,CAAA;AACzD,IAAA,MAAM,mBAAmB,OAAQ,CAAA,KAAA,CAAM,MAAM,CAC3C,CAAA,KAAA,WAAA,CAAY,SAAS,CAAE,CAAA,EAAA,CAAA,CAAA,CAAA;AAEzB,IAAA,IAAI,CAAC,gBAAkB,EAAA;AACrB,MAAA,MAAM,IAAI,KACR,CAAA,2DAAA,CAAA,CAAA;AAAA,KAAA;AAAA,GAAA;AAAA;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/types/api.ts","../src/permissions/util.ts","../src/permissions/createPermission.ts","../src/PermissionClient.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 { ResourcePermission } from '.';\nimport { Permission } from './permission';\n\n/**\n * A request with a UUID identifier, so that batched responses can be matched up with the original\n * requests.\n * @public\n */\nexport type IdentifiedPermissionMessage<T> = T & { id: string };\n\n/**\n * A batch of request or response items.\n * @public\n */\nexport type PermissionMessageBatch<T> = {\n items: IdentifiedPermissionMessage<T>[];\n};\n\n/**\n * The result of an authorization request.\n * @public\n */\nexport enum AuthorizeResult {\n /**\n * The authorization request is denied.\n */\n DENY = 'DENY',\n /**\n * The authorization request is allowed.\n */\n ALLOW = 'ALLOW',\n /**\n * The authorization request is allowed if the provided conditions are met.\n */\n CONDITIONAL = 'CONDITIONAL',\n}\n\n/**\n * A definitive decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.\n *\n * @remarks\n *\n * This indicates that the policy unconditionally allows (or denies) the request.\n *\n * @public\n */\nexport type DefinitivePolicyDecision = {\n result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;\n};\n\n/**\n * A conditional decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.\n *\n * @remarks\n *\n * This indicates that the policy allows authorization for the request, given that the returned\n * conditions hold when evaluated. The conditions will be evaluated by the corresponding plugin\n * which knows about the referenced permission rules.\n *\n * @public\n */\nexport type ConditionalPolicyDecision = {\n result: AuthorizeResult.CONDITIONAL;\n pluginId: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n};\n\n/**\n * A decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.\n *\n * @public\n */\nexport type PolicyDecision =\n | DefinitivePolicyDecision\n | ConditionalPolicyDecision;\n\n/**\n * A condition returned with a CONDITIONAL authorization response.\n *\n * Conditions are a reference to a rule defined by a plugin, and parameters to apply the rule. For\n * example, a rule might be `isOwner` from the catalog-backend, and params may be a list of entity\n * claims from a identity token.\n * @public\n */\nexport type PermissionCondition<\n TResourceType extends string = string,\n TParams extends unknown[] = unknown[],\n> = {\n resourceType: TResourceType;\n rule: string;\n params: TParams;\n};\n\n/**\n * Utility type to represent an array with 1 or more elements.\n * @ignore\n */\ntype NonEmptyArray<T> = [T, ...T[]];\n\n/**\n * Represents a logical AND for the provided criteria.\n * @public\n */\nexport type AllOfCriteria<TQuery> = {\n allOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a logical OR for the provided criteria.\n * @public\n */\nexport type AnyOfCriteria<TQuery> = {\n anyOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a negation of the provided criteria.\n * @public\n */\nexport type NotCriteria<TQuery> = {\n not: PermissionCriteria<TQuery>;\n};\n\n/**\n * Composes several {@link PermissionCondition}s as criteria with a nested AND/OR structure.\n * @public\n */\nexport type PermissionCriteria<TQuery> =\n | AllOfCriteria<TQuery>\n | AnyOfCriteria<TQuery>\n | NotCriteria<TQuery>\n | TQuery;\n\n/**\n * An individual request sent to the permission backend.\n * @public\n */\nexport type EvaluatePermissionRequest = {\n permission: Permission;\n resourceRef?: string;\n};\n\n/**\n * A batch of requests sent to the permission backend.\n * @public\n */\nexport type EvaluatePermissionRequestBatch =\n PermissionMessageBatch<EvaluatePermissionRequest>;\n\n/**\n * An individual response from the permission backend.\n *\n * @remarks\n *\n * This response type is an alias of {@link PolicyDecision} to maintain separation between the\n * {@link @backstage/plugin-permission-node#PermissionPolicy} interface and the permission backend\n * api. They may diverge at some point in the future. The response\n *\n * @public\n */\nexport type EvaluatePermissionResponse = PolicyDecision;\n\n/**\n * A batch of responses from the permission backend.\n * @public\n */\nexport type EvaluatePermissionResponseBatch =\n PermissionMessageBatch<EvaluatePermissionResponse>;\n\n/**\n * Request object for {@link PermissionEvaluator.authorize}. If a {@link ResourcePermission}\n * is provided, it must include a corresponding `resourceRef`.\n * @public\n */\nexport type AuthorizePermissionRequest =\n | {\n permission: Exclude<Permission, ResourcePermission>;\n resourceRef?: never;\n }\n | { permission: ResourcePermission; resourceRef: string };\n\n/**\n * Response object for {@link PermissionEvaluator.authorize}.\n * @public\n */\nexport type AuthorizePermissionResponse = DefinitivePolicyDecision;\n\n/**\n * Request object for {@link PermissionEvaluator.authorizeConditional}.\n * @public\n */\nexport type QueryPermissionRequest = {\n permission: ResourcePermission;\n resourceRef?: never;\n};\n\n/**\n * Response object for {@link PermissionEvaluator.authorizeConditional}.\n * @public\n */\nexport type QueryPermissionResponse = PolicyDecision;\n\n/**\n * A client interacting with the permission backend can implement this evaluator interface.\n *\n * @public\n */\nexport interface PermissionEvaluator {\n /**\n * Evaluates {@link Permission | Permissions} and returns a definitive decision.\n */\n authorize(\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]>;\n\n /**\n * Evaluates {@link ResourcePermission | ResourcePermissions} and returns both definitive and\n * conditional decisions, depending on the configured\n * {@link @backstage/plugin-permission-node#PermissionPolicy}. This method is useful when the\n * caller needs more control over the processing of conditional decisions. For example, a plugin\n * backend may want to use {@link PermissionCriteria | conditions} in a database query instead of\n * evaluating each resource in memory.\n */\n authorizeConditional(\n requests: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<QueryPermissionResponse[]>;\n}\n\n/**\n * Options for {@link PermissionEvaluator} requests.\n * The Backstage identity token should be defined if available.\n * @public\n */\nexport type EvaluatorRequestOptions = {\n token?: string;\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 AuthorizePermissionRequest,\n AuthorizePermissionResponse,\n DefinitivePolicyDecision,\n EvaluatorRequestOptions,\n Permission,\n PermissionAuthorizer,\n PermissionEvaluator,\n QueryPermissionRequest,\n QueryPermissionResponse,\n ResourcePermission,\n} from '../types';\n\n/**\n * Check if the two parameters are equivalent permissions.\n * @public\n */\nexport function isPermission<T extends Permission>(\n permission: Permission,\n comparedPermission: T,\n): permission is T {\n return permission.name === comparedPermission.name;\n}\n\n/**\n * Check if a given permission is a {@link ResourcePermission}. When\n * `resourceType` is supplied as the second parameter, also checks if\n * the permission has the specified resource type.\n * @public\n */\nexport function isResourcePermission<T extends string = string>(\n permission: Permission,\n resourceType?: T,\n): permission is ResourcePermission<T> {\n if (!('resourceType' in permission)) {\n return false;\n }\n\n return !resourceType || permission.resourceType === resourceType;\n}\n\n/**\n * Check if a given permission is related to a create action.\n * @public\n */\nexport function isCreatePermission(permission: Permission) {\n return permission.attributes.action === 'create';\n}\n\n/**\n * Check if a given permission is related to a read action.\n * @public\n */\nexport function isReadPermission(permission: Permission) {\n return permission.attributes.action === 'read';\n}\n\n/**\n * Check if a given permission is related to an update action.\n * @public\n */\nexport function isUpdatePermission(permission: Permission) {\n return permission.attributes.action === 'update';\n}\n\n/**\n * Check if a given permission is related to a delete action.\n * @public\n */\nexport function isDeletePermission(permission: Permission) {\n return permission.attributes.action === 'delete';\n}\n\n/**\n * Convert {@link PermissionAuthorizer} to {@link PermissionEvaluator}.\n *\n * @public\n */\nexport function toPermissionEvaluator(\n permissionAuthorizer: PermissionAuthorizer,\n): PermissionEvaluator {\n return {\n authorize: async (\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]> => {\n const response = await permissionAuthorizer.authorize(requests, options);\n\n return response as DefinitivePolicyDecision[];\n },\n authorizeConditional(\n requests: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<QueryPermissionResponse[]> {\n const parsedRequests =\n requests as unknown as AuthorizePermissionRequest[];\n return permissionAuthorizer.authorize(parsedRequests, options);\n },\n };\n}\n","/*\n * Copyright 2022 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 BasicPermission,\n Permission,\n PermissionAttributes,\n ResourcePermission,\n} from '../types';\n\n/**\n * Utility function for creating a valid {@link ResourcePermission}, inferring\n * the appropriate type and resource type parameter.\n *\n * @public\n */\nexport function createPermission<TResourceType extends string>(input: {\n name: string;\n attributes: PermissionAttributes;\n resourceType: TResourceType;\n}): ResourcePermission<TResourceType>;\n/**\n * Utility function for creating a valid {@link BasicPermission}.\n *\n * @public\n */\nexport function createPermission(input: {\n name: string;\n attributes: PermissionAttributes;\n}): BasicPermission;\nexport function createPermission({\n name,\n attributes,\n resourceType,\n}: {\n name: string;\n attributes: PermissionAttributes;\n resourceType?: string;\n}): Permission {\n if (resourceType) {\n return {\n type: 'resource',\n name,\n attributes,\n resourceType,\n };\n }\n\n return {\n type: 'basic',\n name,\n attributes,\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 { Config } from '@backstage/config';\nimport { ResponseError } from '@backstage/errors';\nimport fetch from 'cross-fetch';\nimport * as uuid from 'uuid';\nimport { z } from 'zod';\nimport {\n AuthorizeResult,\n PermissionMessageBatch,\n PermissionCriteria,\n PermissionCondition,\n PermissionEvaluator,\n QueryPermissionRequest,\n AuthorizePermissionRequest,\n EvaluatorRequestOptions,\n AuthorizePermissionResponse,\n QueryPermissionResponse,\n} from './types/api';\nimport { DiscoveryApi } from './types/discovery';\nimport { AuthorizeRequestOptions } from './types/permission';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z\n .object({\n rule: z.string(),\n resourceType: z.string(),\n params: z.array(z.unknown()),\n })\n .or(z.object({ anyOf: z.array(permissionCriteriaSchema).nonempty() }))\n .or(z.object({ allOf: z.array(permissionCriteriaSchema).nonempty() }))\n .or(z.object({ not: permissionCriteriaSchema })),\n);\n\nconst authorizePermissionResponseSchema: z.ZodSchema<AuthorizePermissionResponse> =\n z.object({\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n });\n\nconst queryPermissionResponseSchema: z.ZodSchema<QueryPermissionResponse> =\n z.union([\n z.object({\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n }),\n z.object({\n result: z.literal(AuthorizeResult.CONDITIONAL),\n pluginId: z.string(),\n resourceType: z.string(),\n conditions: permissionCriteriaSchema,\n }),\n ]);\n\nconst responseSchema = <T>(\n itemSchema: z.ZodSchema<T>,\n ids: Set<string>,\n): z.ZodSchema<PermissionMessageBatch<T>> =>\n z.object({\n items: z\n .array(\n z.intersection(\n z.object({\n id: z.string(),\n }),\n itemSchema,\n ),\n )\n .refine(\n items =>\n items.length === ids.size && items.every(({ id }) => ids.has(id)),\n {\n message: 'Items in response do not match request',\n },\n ),\n });\n\n/**\n * An isomorphic client for requesting authorization for Backstage permissions.\n * @public\n */\nexport class PermissionClient implements PermissionEvaluator {\n private readonly enabled: boolean;\n private readonly discovery: DiscoveryApi;\n\n constructor(options: { discovery: DiscoveryApi; config: Config }) {\n this.discovery = options.discovery;\n this.enabled =\n options.config.getOptionalBoolean('permission.enabled') ?? false;\n }\n\n /**\n * {@inheritdoc PermissionEvaluator.authorize}\n */\n async authorize(\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]> {\n return this.makeRequest(\n requests,\n authorizePermissionResponseSchema,\n options,\n );\n }\n\n /**\n * {@inheritdoc PermissionEvaluator.authorizeConditional}\n */\n async authorizeConditional(\n queries: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<QueryPermissionResponse[]> {\n return this.makeRequest(queries, queryPermissionResponseSchema, options);\n }\n\n private async makeRequest<TQuery, TResult>(\n queries: TQuery[],\n itemSchema: z.ZodSchema<TResult>,\n options?: AuthorizeRequestOptions,\n ) {\n if (!this.enabled) {\n return queries.map(_ => ({ result: AuthorizeResult.ALLOW as const }));\n }\n\n const request: PermissionMessageBatch<TQuery> = {\n items: queries.map(query => ({\n id: uuid.v4(),\n ...query,\n })),\n };\n\n const permissionApi = await this.discovery.getBaseUrl('permission');\n const response = await fetch(`${permissionApi}/authorize`, {\n method: 'POST',\n body: JSON.stringify(request),\n headers: {\n ...this.getAuthorizationHeader(options?.token),\n 'content-type': 'application/json',\n },\n });\n if (!response.ok) {\n throw await ResponseError.fromResponse(response);\n }\n\n const responseBody = await response.json();\n\n const parsedResponse = responseSchema(\n itemSchema,\n new Set(request.items.map(({ id }) => id)),\n ).parse(responseBody);\n\n const responsesById = parsedResponse.items.reduce((acc, r) => {\n acc[r.id] = r;\n return acc;\n }, {} as Record<string, z.infer<typeof itemSchema>>);\n\n return request.items.map(query => responsesById[query.id]);\n }\n\n private getAuthorizationHeader(token?: string): Record<string, string> {\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n}\n"],"names":["z","uuid","fetch","ResponseError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAU,IAAC,eAAe,mBAAmB,CAAC,CAAC,gBAAgB,KAAK;AACpE,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AACpC,EAAE,gBAAgB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;AACtC,EAAE,gBAAgB,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC;AAClD,EAAE,OAAO,gBAAgB,CAAC;AAC1B,CAAC,EAAE,eAAe,IAAI,EAAE;;ACLjB,SAAS,YAAY,CAAC,UAAU,EAAE,kBAAkB,EAAE;AAC7D,EAAE,OAAO,UAAU,CAAC,IAAI,KAAK,kBAAkB,CAAC,IAAI,CAAC;AACrD,CAAC;AACM,SAAS,oBAAoB,CAAC,UAAU,EAAE,YAAY,EAAE;AAC/D,EAAE,IAAI,EAAE,cAAc,IAAI,UAAU,CAAC,EAAE;AACvC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH,EAAE,OAAO,CAAC,YAAY,IAAI,UAAU,CAAC,YAAY,KAAK,YAAY,CAAC;AACnE,CAAC;AACM,SAAS,kBAAkB,CAAC,UAAU,EAA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AAC,IAAI,EAAE,CAAC;AAC/C,IAAI,MAAM,cAAc,GAAG,cAAc,CAAC,UAAU,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AACtH,IAAI,MAAM,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;AAClE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,CAAC;AACjB,KAAK,EAAE,EAAE,CAAC,CAAC;AACX,IAAI,OAAO,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,KAAK,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;AACjE,GAAG;AACH,EAAE,sBAAsB,CAAC,KAAK,EAAE;AAChC,IAAI,OAAO,KAAK,GAAG,EAAE,aAAa,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC;AAC7D,GAAG;AACH;;;;;;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,17 +9,10 @@ declare type PermissionAttributes = {
|
|
|
9
9
|
action?: 'create' | 'read' | 'update' | 'delete';
|
|
10
10
|
};
|
|
11
11
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* Permissions are the "what" part of authorization, the action to be performed. This may be reading
|
|
15
|
-
* an entity from the catalog, executing a software template, or any other action a plugin author
|
|
16
|
-
* may wish to protect.
|
|
17
|
-
*
|
|
18
|
-
* To evaluate authorization, a permission is paired with a Backstage identity (the "who") and
|
|
19
|
-
* evaluated using an authorization policy.
|
|
12
|
+
* Generic type for building {@link Permission} types.
|
|
20
13
|
* @public
|
|
21
14
|
*/
|
|
22
|
-
declare type
|
|
15
|
+
declare type PermissionBase<TType extends string, TFields extends object> = {
|
|
23
16
|
/**
|
|
24
17
|
* The name of the permission.
|
|
25
18
|
*/
|
|
@@ -30,20 +23,53 @@ declare type Permission = {
|
|
|
30
23
|
* all by name.
|
|
31
24
|
*/
|
|
32
25
|
attributes: PermissionAttributes;
|
|
26
|
+
} & {
|
|
33
27
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
28
|
+
* String value indicating the type of the permission (e.g. 'basic',
|
|
29
|
+
* 'resource'). The allowed authorization flows in the permission system
|
|
30
|
+
* depend on the type. For example, a `resourceRef` should only be provided
|
|
31
|
+
* when authorizing permissions of type 'resource'.
|
|
32
|
+
*/
|
|
33
|
+
type: TType;
|
|
34
|
+
} & TFields;
|
|
35
|
+
/**
|
|
36
|
+
* A permission that can be checked through authorization.
|
|
37
|
+
*
|
|
38
|
+
* @remarks
|
|
39
|
+
*
|
|
40
|
+
* Permissions are the "what" part of authorization, the action to be performed. This may be reading
|
|
41
|
+
* an entity from the catalog, executing a software template, or any other action a plugin author
|
|
42
|
+
* may wish to protect.
|
|
43
|
+
*
|
|
44
|
+
* To evaluate authorization, a permission is paired with a Backstage identity (the "who") and
|
|
45
|
+
* evaluated using an authorization policy.
|
|
46
|
+
* @public
|
|
47
|
+
*/
|
|
48
|
+
declare type Permission = BasicPermission | ResourcePermission;
|
|
49
|
+
/**
|
|
50
|
+
* A standard {@link Permission} with no additional capabilities or restrictions.
|
|
51
|
+
* @public
|
|
52
|
+
*/
|
|
53
|
+
declare type BasicPermission = PermissionBase<'basic', {}>;
|
|
54
|
+
/**
|
|
55
|
+
* ResourcePermissions are {@link Permission}s that can be authorized based on
|
|
56
|
+
* characteristics of a resource such a catalog entity.
|
|
57
|
+
* @public
|
|
58
|
+
*/
|
|
59
|
+
declare type ResourcePermission<TResourceType extends string = string> = PermissionBase<'resource', {
|
|
60
|
+
/**
|
|
61
|
+
* Denotes the type of the resource whose resourceRef should be passed when
|
|
37
62
|
* authorizing.
|
|
38
63
|
*/
|
|
39
|
-
resourceType
|
|
40
|
-
}
|
|
64
|
+
resourceType: TResourceType;
|
|
65
|
+
}>;
|
|
41
66
|
/**
|
|
42
67
|
* A client interacting with the permission backend can implement this authorizer interface.
|
|
43
68
|
* @public
|
|
69
|
+
* @deprecated Use {@link @backstage/plugin-permission-common#PermissionEvaluator} instead
|
|
44
70
|
*/
|
|
45
71
|
interface PermissionAuthorizer {
|
|
46
|
-
authorize(
|
|
72
|
+
authorize(requests: EvaluatePermissionRequest[], options?: AuthorizeRequestOptions): Promise<EvaluatePermissionResponse[]>;
|
|
47
73
|
}
|
|
48
74
|
/**
|
|
49
75
|
* Options for authorization requests.
|
|
@@ -58,9 +84,16 @@ declare type AuthorizeRequestOptions = {
|
|
|
58
84
|
* requests.
|
|
59
85
|
* @public
|
|
60
86
|
*/
|
|
61
|
-
declare type
|
|
87
|
+
declare type IdentifiedPermissionMessage<T> = T & {
|
|
62
88
|
id: string;
|
|
63
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* A batch of request or response items.
|
|
92
|
+
* @public
|
|
93
|
+
*/
|
|
94
|
+
declare type PermissionMessageBatch<T> = {
|
|
95
|
+
items: IdentifiedPermissionMessage<T>[];
|
|
96
|
+
};
|
|
64
97
|
/**
|
|
65
98
|
* The result of an authorization request.
|
|
66
99
|
* @public
|
|
@@ -80,20 +113,40 @@ declare enum AuthorizeResult {
|
|
|
80
113
|
CONDITIONAL = "CONDITIONAL"
|
|
81
114
|
}
|
|
82
115
|
/**
|
|
83
|
-
*
|
|
116
|
+
* A definitive decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.
|
|
117
|
+
*
|
|
118
|
+
* @remarks
|
|
119
|
+
*
|
|
120
|
+
* This indicates that the policy unconditionally allows (or denies) the request.
|
|
121
|
+
*
|
|
84
122
|
* @public
|
|
85
123
|
*/
|
|
86
|
-
declare type
|
|
87
|
-
|
|
88
|
-
resourceRef?: string;
|
|
124
|
+
declare type DefinitivePolicyDecision = {
|
|
125
|
+
result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;
|
|
89
126
|
};
|
|
90
127
|
/**
|
|
91
|
-
* A
|
|
128
|
+
* A conditional decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.
|
|
129
|
+
*
|
|
130
|
+
* @remarks
|
|
131
|
+
*
|
|
132
|
+
* This indicates that the policy allows authorization for the request, given that the returned
|
|
133
|
+
* conditions hold when evaluated. The conditions will be evaluated by the corresponding plugin
|
|
134
|
+
* which knows about the referenced permission rules.
|
|
135
|
+
*
|
|
92
136
|
* @public
|
|
93
137
|
*/
|
|
94
|
-
declare type
|
|
95
|
-
|
|
138
|
+
declare type ConditionalPolicyDecision = {
|
|
139
|
+
result: AuthorizeResult.CONDITIONAL;
|
|
140
|
+
pluginId: string;
|
|
141
|
+
resourceType: string;
|
|
142
|
+
conditions: PermissionCriteria<PermissionCondition>;
|
|
96
143
|
};
|
|
144
|
+
/**
|
|
145
|
+
* A decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.
|
|
146
|
+
*
|
|
147
|
+
* @public
|
|
148
|
+
*/
|
|
149
|
+
declare type PolicyDecision = DefinitivePolicyDecision | ConditionalPolicyDecision;
|
|
97
150
|
/**
|
|
98
151
|
* A condition returned with a CONDITIONAL authorization response.
|
|
99
152
|
*
|
|
@@ -102,7 +155,8 @@ declare type AuthorizeRequest = {
|
|
|
102
155
|
* claims from a identity token.
|
|
103
156
|
* @public
|
|
104
157
|
*/
|
|
105
|
-
declare type PermissionCondition<TParams extends unknown[] = unknown[]> = {
|
|
158
|
+
declare type PermissionCondition<TResourceType extends string = string, TParams extends unknown[] = unknown[]> = {
|
|
159
|
+
resourceType: TResourceType;
|
|
106
160
|
rule: string;
|
|
107
161
|
params: TParams;
|
|
108
162
|
};
|
|
@@ -138,21 +192,92 @@ declare type NotCriteria<TQuery> = {
|
|
|
138
192
|
*/
|
|
139
193
|
declare type PermissionCriteria<TQuery> = AllOfCriteria<TQuery> | AnyOfCriteria<TQuery> | NotCriteria<TQuery> | TQuery;
|
|
140
194
|
/**
|
|
141
|
-
* An individual
|
|
195
|
+
* An individual request sent to the permission backend.
|
|
142
196
|
* @public
|
|
143
197
|
*/
|
|
144
|
-
declare type
|
|
145
|
-
|
|
198
|
+
declare type EvaluatePermissionRequest = {
|
|
199
|
+
permission: Permission;
|
|
200
|
+
resourceRef?: string;
|
|
201
|
+
};
|
|
202
|
+
/**
|
|
203
|
+
* A batch of requests sent to the permission backend.
|
|
204
|
+
* @public
|
|
205
|
+
*/
|
|
206
|
+
declare type EvaluatePermissionRequestBatch = PermissionMessageBatch<EvaluatePermissionRequest>;
|
|
207
|
+
/**
|
|
208
|
+
* An individual response from the permission backend.
|
|
209
|
+
*
|
|
210
|
+
* @remarks
|
|
211
|
+
*
|
|
212
|
+
* This response type is an alias of {@link PolicyDecision} to maintain separation between the
|
|
213
|
+
* {@link @backstage/plugin-permission-node#PermissionPolicy} interface and the permission backend
|
|
214
|
+
* api. They may diverge at some point in the future. The response
|
|
215
|
+
*
|
|
216
|
+
* @public
|
|
217
|
+
*/
|
|
218
|
+
declare type EvaluatePermissionResponse = PolicyDecision;
|
|
219
|
+
/**
|
|
220
|
+
* A batch of responses from the permission backend.
|
|
221
|
+
* @public
|
|
222
|
+
*/
|
|
223
|
+
declare type EvaluatePermissionResponseBatch = PermissionMessageBatch<EvaluatePermissionResponse>;
|
|
224
|
+
/**
|
|
225
|
+
* Request object for {@link PermissionEvaluator.authorize}. If a {@link ResourcePermission}
|
|
226
|
+
* is provided, it must include a corresponding `resourceRef`.
|
|
227
|
+
* @public
|
|
228
|
+
*/
|
|
229
|
+
declare type AuthorizePermissionRequest = {
|
|
230
|
+
permission: Exclude<Permission, ResourcePermission>;
|
|
231
|
+
resourceRef?: never;
|
|
146
232
|
} | {
|
|
147
|
-
|
|
148
|
-
|
|
233
|
+
permission: ResourcePermission;
|
|
234
|
+
resourceRef: string;
|
|
149
235
|
};
|
|
150
236
|
/**
|
|
151
|
-
*
|
|
237
|
+
* Response object for {@link PermissionEvaluator.authorize}.
|
|
238
|
+
* @public
|
|
239
|
+
*/
|
|
240
|
+
declare type AuthorizePermissionResponse = DefinitivePolicyDecision;
|
|
241
|
+
/**
|
|
242
|
+
* Request object for {@link PermissionEvaluator.authorizeConditional}.
|
|
152
243
|
* @public
|
|
153
244
|
*/
|
|
154
|
-
declare type
|
|
155
|
-
|
|
245
|
+
declare type QueryPermissionRequest = {
|
|
246
|
+
permission: ResourcePermission;
|
|
247
|
+
resourceRef?: never;
|
|
248
|
+
};
|
|
249
|
+
/**
|
|
250
|
+
* Response object for {@link PermissionEvaluator.authorizeConditional}.
|
|
251
|
+
* @public
|
|
252
|
+
*/
|
|
253
|
+
declare type QueryPermissionResponse = PolicyDecision;
|
|
254
|
+
/**
|
|
255
|
+
* A client interacting with the permission backend can implement this evaluator interface.
|
|
256
|
+
*
|
|
257
|
+
* @public
|
|
258
|
+
*/
|
|
259
|
+
interface PermissionEvaluator {
|
|
260
|
+
/**
|
|
261
|
+
* Evaluates {@link Permission | Permissions} and returns a definitive decision.
|
|
262
|
+
*/
|
|
263
|
+
authorize(requests: AuthorizePermissionRequest[], options?: EvaluatorRequestOptions): Promise<AuthorizePermissionResponse[]>;
|
|
264
|
+
/**
|
|
265
|
+
* Evaluates {@link ResourcePermission | ResourcePermissions} and returns both definitive and
|
|
266
|
+
* conditional decisions, depending on the configured
|
|
267
|
+
* {@link @backstage/plugin-permission-node#PermissionPolicy}. This method is useful when the
|
|
268
|
+
* caller needs more control over the processing of conditional decisions. For example, a plugin
|
|
269
|
+
* backend may want to use {@link PermissionCriteria | conditions} in a database query instead of
|
|
270
|
+
* evaluating each resource in memory.
|
|
271
|
+
*/
|
|
272
|
+
authorizeConditional(requests: QueryPermissionRequest[], options?: EvaluatorRequestOptions): Promise<QueryPermissionResponse[]>;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Options for {@link PermissionEvaluator} requests.
|
|
276
|
+
* The Backstage identity token should be defined if available.
|
|
277
|
+
* @public
|
|
278
|
+
*/
|
|
279
|
+
declare type EvaluatorRequestOptions = {
|
|
280
|
+
token?: string;
|
|
156
281
|
};
|
|
157
282
|
|
|
158
283
|
/**
|
|
@@ -164,6 +289,18 @@ declare type DiscoveryApi = {
|
|
|
164
289
|
getBaseUrl(pluginId: string): Promise<string>;
|
|
165
290
|
};
|
|
166
291
|
|
|
292
|
+
/**
|
|
293
|
+
* Check if the two parameters are equivalent permissions.
|
|
294
|
+
* @public
|
|
295
|
+
*/
|
|
296
|
+
declare function isPermission<T extends Permission>(permission: Permission, comparedPermission: T): permission is T;
|
|
297
|
+
/**
|
|
298
|
+
* Check if a given permission is a {@link ResourcePermission}. When
|
|
299
|
+
* `resourceType` is supplied as the second parameter, also checks if
|
|
300
|
+
* the permission has the specified resource type.
|
|
301
|
+
* @public
|
|
302
|
+
*/
|
|
303
|
+
declare function isResourcePermission<T extends string = string>(permission: Permission, resourceType?: T): permission is ResourcePermission<T>;
|
|
167
304
|
/**
|
|
168
305
|
* Check if a given permission is related to a create action.
|
|
169
306
|
* @public
|
|
@@ -184,12 +321,39 @@ declare function isUpdatePermission(permission: Permission): boolean;
|
|
|
184
321
|
* @public
|
|
185
322
|
*/
|
|
186
323
|
declare function isDeletePermission(permission: Permission): boolean;
|
|
324
|
+
/**
|
|
325
|
+
* Convert {@link PermissionAuthorizer} to {@link PermissionEvaluator}.
|
|
326
|
+
*
|
|
327
|
+
* @public
|
|
328
|
+
*/
|
|
329
|
+
declare function toPermissionEvaluator(permissionAuthorizer: PermissionAuthorizer): PermissionEvaluator;
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Utility function for creating a valid {@link ResourcePermission}, inferring
|
|
333
|
+
* the appropriate type and resource type parameter.
|
|
334
|
+
*
|
|
335
|
+
* @public
|
|
336
|
+
*/
|
|
337
|
+
declare function createPermission<TResourceType extends string>(input: {
|
|
338
|
+
name: string;
|
|
339
|
+
attributes: PermissionAttributes;
|
|
340
|
+
resourceType: TResourceType;
|
|
341
|
+
}): ResourcePermission<TResourceType>;
|
|
342
|
+
/**
|
|
343
|
+
* Utility function for creating a valid {@link BasicPermission}.
|
|
344
|
+
*
|
|
345
|
+
* @public
|
|
346
|
+
*/
|
|
347
|
+
declare function createPermission(input: {
|
|
348
|
+
name: string;
|
|
349
|
+
attributes: PermissionAttributes;
|
|
350
|
+
}): BasicPermission;
|
|
187
351
|
|
|
188
352
|
/**
|
|
189
353
|
* An isomorphic client for requesting authorization for Backstage permissions.
|
|
190
354
|
* @public
|
|
191
355
|
*/
|
|
192
|
-
declare class PermissionClient implements
|
|
356
|
+
declare class PermissionClient implements PermissionEvaluator {
|
|
193
357
|
private readonly enabled;
|
|
194
358
|
private readonly discovery;
|
|
195
359
|
constructor(options: {
|
|
@@ -197,24 +361,15 @@ declare class PermissionClient implements PermissionAuthorizer {
|
|
|
197
361
|
config: Config;
|
|
198
362
|
});
|
|
199
363
|
/**
|
|
200
|
-
*
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
* Permissions can be imported from plugins exposing them, such as `catalogEntityReadPermission`.
|
|
207
|
-
*
|
|
208
|
-
* The response will be either ALLOW or DENY when either the permission has no resourceType, or a
|
|
209
|
-
* resourceRef is provided in the request. For permissions with a resourceType, CONDITIONAL may be
|
|
210
|
-
* returned if no resourceRef is provided in the request. Conditional responses are intended only
|
|
211
|
-
* for backends which have access to the data source for permissioned resources, so that filters
|
|
212
|
-
* can be applied when loading collections of resources.
|
|
213
|
-
* @public
|
|
364
|
+
* {@inheritdoc PermissionEvaluator.authorize}
|
|
365
|
+
*/
|
|
366
|
+
authorize(requests: AuthorizePermissionRequest[], options?: EvaluatorRequestOptions): Promise<AuthorizePermissionResponse[]>;
|
|
367
|
+
/**
|
|
368
|
+
* {@inheritdoc PermissionEvaluator.authorizeConditional}
|
|
214
369
|
*/
|
|
215
|
-
|
|
370
|
+
authorizeConditional(queries: QueryPermissionRequest[], options?: EvaluatorRequestOptions): Promise<QueryPermissionResponse[]>;
|
|
371
|
+
private makeRequest;
|
|
216
372
|
private getAuthorizationHeader;
|
|
217
|
-
private assertValidResponse;
|
|
218
373
|
}
|
|
219
374
|
|
|
220
|
-
export { AllOfCriteria, AnyOfCriteria,
|
|
375
|
+
export { AllOfCriteria, AnyOfCriteria, AuthorizePermissionRequest, AuthorizePermissionResponse, AuthorizeRequestOptions, AuthorizeResult, BasicPermission, ConditionalPolicyDecision, DefinitivePolicyDecision, DiscoveryApi, EvaluatePermissionRequest, EvaluatePermissionRequestBatch, EvaluatePermissionResponse, EvaluatePermissionResponseBatch, EvaluatorRequestOptions, IdentifiedPermissionMessage, NotCriteria, Permission, PermissionAttributes, PermissionAuthorizer, PermissionBase, PermissionClient, PermissionCondition, PermissionCriteria, PermissionEvaluator, PermissionMessageBatch, PolicyDecision, QueryPermissionRequest, QueryPermissionResponse, ResourcePermission, createPermission, isCreatePermission, isDeletePermission, isPermission, isReadPermission, isResourcePermission, isUpdatePermission, toPermissionEvaluator };
|
package/dist/index.esm.js
CHANGED
|
@@ -10,6 +10,15 @@ var AuthorizeResult = /* @__PURE__ */ ((AuthorizeResult2) => {
|
|
|
10
10
|
return AuthorizeResult2;
|
|
11
11
|
})(AuthorizeResult || {});
|
|
12
12
|
|
|
13
|
+
function isPermission(permission, comparedPermission) {
|
|
14
|
+
return permission.name === comparedPermission.name;
|
|
15
|
+
}
|
|
16
|
+
function isResourcePermission(permission, resourceType) {
|
|
17
|
+
if (!("resourceType" in permission)) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
return !resourceType || permission.resourceType === resourceType;
|
|
21
|
+
}
|
|
13
22
|
function isCreatePermission(permission) {
|
|
14
23
|
return permission.attributes.action === "create";
|
|
15
24
|
}
|
|
@@ -22,20 +31,64 @@ function isUpdatePermission(permission) {
|
|
|
22
31
|
function isDeletePermission(permission) {
|
|
23
32
|
return permission.attributes.action === "delete";
|
|
24
33
|
}
|
|
34
|
+
function toPermissionEvaluator(permissionAuthorizer) {
|
|
35
|
+
return {
|
|
36
|
+
authorize: async (requests, options) => {
|
|
37
|
+
const response = await permissionAuthorizer.authorize(requests, options);
|
|
38
|
+
return response;
|
|
39
|
+
},
|
|
40
|
+
authorizeConditional(requests, options) {
|
|
41
|
+
const parsedRequests = requests;
|
|
42
|
+
return permissionAuthorizer.authorize(parsedRequests, options);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function createPermission({
|
|
48
|
+
name,
|
|
49
|
+
attributes,
|
|
50
|
+
resourceType
|
|
51
|
+
}) {
|
|
52
|
+
if (resourceType) {
|
|
53
|
+
return {
|
|
54
|
+
type: "resource",
|
|
55
|
+
name,
|
|
56
|
+
attributes,
|
|
57
|
+
resourceType
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
type: "basic",
|
|
62
|
+
name,
|
|
63
|
+
attributes
|
|
64
|
+
};
|
|
65
|
+
}
|
|
25
66
|
|
|
26
67
|
const permissionCriteriaSchema = z.lazy(() => z.object({
|
|
27
68
|
rule: z.string(),
|
|
69
|
+
resourceType: z.string(),
|
|
28
70
|
params: z.array(z.unknown())
|
|
29
|
-
}).
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
71
|
+
}).or(z.object({ anyOf: z.array(permissionCriteriaSchema).nonempty() })).or(z.object({ allOf: z.array(permissionCriteriaSchema).nonempty() })).or(z.object({ not: permissionCriteriaSchema })));
|
|
72
|
+
const authorizePermissionResponseSchema = z.object({
|
|
73
|
+
result: z.literal(AuthorizeResult.ALLOW).or(z.literal(AuthorizeResult.DENY))
|
|
74
|
+
});
|
|
75
|
+
const queryPermissionResponseSchema = z.union([
|
|
76
|
+
z.object({
|
|
33
77
|
result: z.literal(AuthorizeResult.ALLOW).or(z.literal(AuthorizeResult.DENY))
|
|
34
|
-
})
|
|
35
|
-
|
|
78
|
+
}),
|
|
79
|
+
z.object({
|
|
36
80
|
result: z.literal(AuthorizeResult.CONDITIONAL),
|
|
81
|
+
pluginId: z.string(),
|
|
82
|
+
resourceType: z.string(),
|
|
37
83
|
conditions: permissionCriteriaSchema
|
|
38
|
-
})
|
|
84
|
+
})
|
|
85
|
+
]);
|
|
86
|
+
const responseSchema = (itemSchema, ids) => z.object({
|
|
87
|
+
items: z.array(z.intersection(z.object({
|
|
88
|
+
id: z.string()
|
|
89
|
+
}), itemSchema)).refine((items) => items.length === ids.size && items.every(({ id }) => ids.has(id)), {
|
|
90
|
+
message: "Items in response do not match request"
|
|
91
|
+
})
|
|
39
92
|
});
|
|
40
93
|
class PermissionClient {
|
|
41
94
|
constructor(options) {
|
|
@@ -43,7 +96,13 @@ class PermissionClient {
|
|
|
43
96
|
this.discovery = options.discovery;
|
|
44
97
|
this.enabled = (_a = options.config.getOptionalBoolean("permission.enabled")) != null ? _a : false;
|
|
45
98
|
}
|
|
46
|
-
async authorize(
|
|
99
|
+
async authorize(requests, options) {
|
|
100
|
+
return this.makeRequest(requests, authorizePermissionResponseSchema, options);
|
|
101
|
+
}
|
|
102
|
+
async authorizeConditional(queries, options) {
|
|
103
|
+
return this.makeRequest(queries, queryPermissionResponseSchema, options);
|
|
104
|
+
}
|
|
105
|
+
async makeRequest(queries, itemSchema, options) {
|
|
47
106
|
if (!this.enabled) {
|
|
48
107
|
return queries.map((_) => ({ result: AuthorizeResult.ALLOW }));
|
|
49
108
|
}
|
|
@@ -66,8 +125,8 @@ class PermissionClient {
|
|
|
66
125
|
throw await ResponseError.fromResponse(response);
|
|
67
126
|
}
|
|
68
127
|
const responseBody = await response.json();
|
|
69
|
-
|
|
70
|
-
const responsesById =
|
|
128
|
+
const parsedResponse = responseSchema(itemSchema, new Set(request.items.map(({ id }) => id))).parse(responseBody);
|
|
129
|
+
const responsesById = parsedResponse.items.reduce((acc, r) => {
|
|
71
130
|
acc[r.id] = r;
|
|
72
131
|
return acc;
|
|
73
132
|
}, {});
|
|
@@ -76,15 +135,7 @@ class PermissionClient {
|
|
|
76
135
|
getAuthorizationHeader(token) {
|
|
77
136
|
return token ? { Authorization: `Bearer ${token}` } : {};
|
|
78
137
|
}
|
|
79
|
-
assertValidResponse(request, json) {
|
|
80
|
-
const authorizedResponses = responseSchema.parse(json);
|
|
81
|
-
const responseIds = authorizedResponses.items.map((r) => r.id);
|
|
82
|
-
const hasAllRequestIds = request.items.every((r) => responseIds.includes(r.id));
|
|
83
|
-
if (!hasAllRequestIds) {
|
|
84
|
-
throw new Error("Unexpected authorization response from permission-backend");
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
138
|
}
|
|
88
139
|
|
|
89
|
-
export { AuthorizeResult, PermissionClient, isCreatePermission, isDeletePermission, isReadPermission, isUpdatePermission };
|
|
140
|
+
export { AuthorizeResult, PermissionClient, createPermission, isCreatePermission, isDeletePermission, isPermission, isReadPermission, isResourcePermission, isUpdatePermission, toPermissionEvaluator };
|
|
90
141
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/types/api.ts","../src/permissions/util.ts","../src/PermissionClient.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 { Permission } from './permission';\n\n/**\n * A request with a UUID identifier, so that batched responses can be matched up with the original\n * requests.\n * @public\n */\nexport type Identified<T> = T & { id: string };\n\n/**\n * The result of an authorization request.\n * @public\n */\nexport enum AuthorizeResult {\n /**\n * The authorization request is denied.\n */\n DENY = 'DENY',\n /**\n * The authorization request is allowed.\n */\n ALLOW = 'ALLOW',\n /**\n * The authorization request is allowed if the provided conditions are met.\n */\n CONDITIONAL = 'CONDITIONAL',\n}\n\n/**\n * An individual authorization request for {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeQuery = {\n permission: Permission;\n resourceRef?: string;\n};\n\n/**\n * A batch of authorization requests from {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeRequest = {\n items: Identified<AuthorizeQuery>[];\n};\n\n/**\n * A condition returned with a CONDITIONAL authorization response.\n *\n * Conditions are a reference to a rule defined by a plugin, and parameters to apply the rule. For\n * example, a rule might be `isOwner` from the catalog-backend, and params may be a list of entity\n * claims from a identity token.\n * @public\n */\nexport type PermissionCondition<TParams extends unknown[] = unknown[]> = {\n rule: string;\n params: TParams;\n};\n\n/**\n * Utility type to represent an array with 1 or more elements.\n * @ignore\n */\ntype NonEmptyArray<T> = [T, ...T[]];\n\n/**\n * Represents a logical AND for the provided criteria.\n * @public\n */\nexport type AllOfCriteria<TQuery> = {\n allOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a logical OR for the provided criteria.\n * @public\n */\nexport type AnyOfCriteria<TQuery> = {\n anyOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a negation of the provided criteria.\n * @public\n */\nexport type NotCriteria<TQuery> = {\n not: PermissionCriteria<TQuery>;\n};\n\n/**\n * Composes several {@link PermissionCondition}s as criteria with a nested AND/OR structure.\n * @public\n */\nexport type PermissionCriteria<TQuery> =\n | AllOfCriteria<TQuery>\n | AnyOfCriteria<TQuery>\n | NotCriteria<TQuery>\n | TQuery;\n\n/**\n * An individual authorization response from {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeDecision =\n | { result: AuthorizeResult.ALLOW | AuthorizeResult.DENY }\n | {\n result: AuthorizeResult.CONDITIONAL;\n conditions: PermissionCriteria<PermissionCondition>;\n };\n\n/**\n * A batch of authorization responses from {@link PermissionClient#authorize}.\n * @public\n */\nexport type AuthorizeResponse = {\n items: Identified<AuthorizeDecision>[];\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 { Permission } from '../types';\n\n/**\n * Check if a given permission is related to a create action.\n * @public\n */\nexport function isCreatePermission(permission: Permission) {\n return permission.attributes.action === 'create';\n}\n\n/**\n * Check if a given permission is related to a read action.\n * @public\n */\nexport function isReadPermission(permission: Permission) {\n return permission.attributes.action === 'read';\n}\n\n/**\n * Check if a given permission is related to an update action.\n * @public\n */\nexport function isUpdatePermission(permission: Permission) {\n return permission.attributes.action === 'update';\n}\n\n/**\n * Check if a given permission is related to a delete action.\n * @public\n */\nexport function isDeletePermission(permission: Permission) {\n return permission.attributes.action === 'delete';\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 { Config } from '@backstage/config';\nimport { ResponseError } from '@backstage/errors';\nimport fetch from 'cross-fetch';\nimport * as uuid from 'uuid';\nimport { z } from 'zod';\nimport {\n AuthorizeResult,\n AuthorizeQuery,\n AuthorizeDecision,\n Identified,\n PermissionCriteria,\n PermissionCondition,\n AuthorizeResponse,\n AuthorizeRequest,\n} from './types/api';\nimport { DiscoveryApi } from './types/discovery';\nimport {\n PermissionAuthorizer,\n AuthorizeRequestOptions,\n} from './types/permission';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z\n .object({\n rule: z.string(),\n params: z.array(z.unknown()),\n })\n .strict()\n .or(\n z\n .object({ anyOf: z.array(permissionCriteriaSchema).nonempty() })\n .strict(),\n )\n .or(\n z\n .object({ allOf: z.array(permissionCriteriaSchema).nonempty() })\n .strict(),\n )\n .or(z.object({ not: permissionCriteriaSchema }).strict()),\n);\n\nconst responseSchema = z.object({\n items: z.array(\n z\n .object({\n id: z.string(),\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n })\n .or(\n z.object({\n id: z.string(),\n result: z.literal(AuthorizeResult.CONDITIONAL),\n conditions: permissionCriteriaSchema,\n }),\n ),\n ),\n});\n\n/**\n * An isomorphic client for requesting authorization for Backstage permissions.\n * @public\n */\nexport class PermissionClient implements PermissionAuthorizer {\n private readonly enabled: boolean;\n private readonly discovery: DiscoveryApi;\n\n constructor(options: { discovery: DiscoveryApi; config: Config }) {\n this.discovery = options.discovery;\n this.enabled =\n options.config.getOptionalBoolean('permission.enabled') ?? false;\n }\n\n /**\n * Request authorization from the permission-backend for the given set of permissions.\n *\n * Authorization requests check that a given Backstage user can perform a protected operation,\n * potentially for a specific resource (such as a catalog entity). The Backstage identity token\n * should be included in the `options` if available.\n *\n * Permissions can be imported from plugins exposing them, such as `catalogEntityReadPermission`.\n *\n * The response will be either ALLOW or DENY when either the permission has no resourceType, or a\n * resourceRef is provided in the request. For permissions with a resourceType, CONDITIONAL may be\n * returned if no resourceRef is provided in the request. Conditional responses are intended only\n * for backends which have access to the data source for permissioned resources, so that filters\n * can be applied when loading collections of resources.\n * @public\n */\n async authorize(\n queries: AuthorizeQuery[],\n options?: AuthorizeRequestOptions,\n ): Promise<AuthorizeDecision[]> {\n // TODO(permissions): it would be great to provide some kind of typing guarantee that\n // conditional responses will only ever be returned for requests containing a resourceType\n // but no resourceRef. That way clients who aren't prepared to handle filtering according\n // to conditions can be guaranteed that they won't unexpectedly get a CONDITIONAL response.\n\n if (!this.enabled) {\n return queries.map(_ => ({ result: AuthorizeResult.ALLOW }));\n }\n\n const request: AuthorizeRequest = {\n items: queries.map(query => ({\n id: uuid.v4(),\n ...query,\n })),\n };\n\n const permissionApi = await this.discovery.getBaseUrl('permission');\n const response = await fetch(`${permissionApi}/authorize`, {\n method: 'POST',\n body: JSON.stringify(request),\n headers: {\n ...this.getAuthorizationHeader(options?.token),\n 'content-type': 'application/json',\n },\n });\n if (!response.ok) {\n throw await ResponseError.fromResponse(response);\n }\n\n const responseBody = await response.json();\n this.assertValidResponse(request, responseBody);\n\n const responsesById = responseBody.items.reduce((acc, r) => {\n acc[r.id] = r;\n return acc;\n }, {} as Record<string, Identified<AuthorizeDecision>>);\n\n return request.items.map(query => responsesById[query.id]);\n }\n\n private getAuthorizationHeader(token?: string): Record<string, string> {\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n\n private assertValidResponse(\n request: AuthorizeRequest,\n json: any,\n ): asserts json is AuthorizeResponse {\n const authorizedResponses = responseSchema.parse(json);\n const responseIds = authorizedResponses.items.map(r => r.id);\n const hasAllRequestIds = request.items.every(r =>\n responseIds.includes(r.id),\n );\n if (!hasAllRequestIds) {\n throw new Error(\n 'Unexpected authorization response from permission-backend',\n );\n }\n }\n}\n"],"names":[],"mappings":";;;;;AA6BY,IAAA,eAAA,qBAAA,gBAAL,KAAA;AAIL,EAAO,gBAAA,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;AAIP,EAAQ,gBAAA,CAAA,OAAA,CAAA,GAAA,OAAA,CAAA;AAIR,EAAc,gBAAA,CAAA,aAAA,CAAA,GAAA,aAAA,CAAA;AAZJ,EAAA,OAAA,gBAAA,CAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;ACPL,SAAA,kBAAA,CAA4B,UAA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,GAAA,CAAI,OAAK,CAAE,CAAA,EAAA,CAAA,CAAA;AACzD,IAAA,MAAM,mBAAmB,OAAQ,CAAA,KAAA,CAAM,MAAM,CAC3C,CAAA,KAAA,WAAA,CAAY,SAAS,CAAE,CAAA,EAAA,CAAA,CAAA,CAAA;AAEzB,IAAA,IAAI,CAAC,gBAAkB,EAAA;AACrB,MAAA,MAAM,IAAI,KACR,CAAA,2DAAA,CAAA,CAAA;AAAA,KAAA;AAAA,GAAA;AAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/types/api.ts","../src/permissions/util.ts","../src/permissions/createPermission.ts","../src/PermissionClient.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 { ResourcePermission } from '.';\nimport { Permission } from './permission';\n\n/**\n * A request with a UUID identifier, so that batched responses can be matched up with the original\n * requests.\n * @public\n */\nexport type IdentifiedPermissionMessage<T> = T & { id: string };\n\n/**\n * A batch of request or response items.\n * @public\n */\nexport type PermissionMessageBatch<T> = {\n items: IdentifiedPermissionMessage<T>[];\n};\n\n/**\n * The result of an authorization request.\n * @public\n */\nexport enum AuthorizeResult {\n /**\n * The authorization request is denied.\n */\n DENY = 'DENY',\n /**\n * The authorization request is allowed.\n */\n ALLOW = 'ALLOW',\n /**\n * The authorization request is allowed if the provided conditions are met.\n */\n CONDITIONAL = 'CONDITIONAL',\n}\n\n/**\n * A definitive decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.\n *\n * @remarks\n *\n * This indicates that the policy unconditionally allows (or denies) the request.\n *\n * @public\n */\nexport type DefinitivePolicyDecision = {\n result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;\n};\n\n/**\n * A conditional decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.\n *\n * @remarks\n *\n * This indicates that the policy allows authorization for the request, given that the returned\n * conditions hold when evaluated. The conditions will be evaluated by the corresponding plugin\n * which knows about the referenced permission rules.\n *\n * @public\n */\nexport type ConditionalPolicyDecision = {\n result: AuthorizeResult.CONDITIONAL;\n pluginId: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n};\n\n/**\n * A decision returned by the {@link @backstage/plugin-permission-node#PermissionPolicy}.\n *\n * @public\n */\nexport type PolicyDecision =\n | DefinitivePolicyDecision\n | ConditionalPolicyDecision;\n\n/**\n * A condition returned with a CONDITIONAL authorization response.\n *\n * Conditions are a reference to a rule defined by a plugin, and parameters to apply the rule. For\n * example, a rule might be `isOwner` from the catalog-backend, and params may be a list of entity\n * claims from a identity token.\n * @public\n */\nexport type PermissionCondition<\n TResourceType extends string = string,\n TParams extends unknown[] = unknown[],\n> = {\n resourceType: TResourceType;\n rule: string;\n params: TParams;\n};\n\n/**\n * Utility type to represent an array with 1 or more elements.\n * @ignore\n */\ntype NonEmptyArray<T> = [T, ...T[]];\n\n/**\n * Represents a logical AND for the provided criteria.\n * @public\n */\nexport type AllOfCriteria<TQuery> = {\n allOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a logical OR for the provided criteria.\n * @public\n */\nexport type AnyOfCriteria<TQuery> = {\n anyOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represents a negation of the provided criteria.\n * @public\n */\nexport type NotCriteria<TQuery> = {\n not: PermissionCriteria<TQuery>;\n};\n\n/**\n * Composes several {@link PermissionCondition}s as criteria with a nested AND/OR structure.\n * @public\n */\nexport type PermissionCriteria<TQuery> =\n | AllOfCriteria<TQuery>\n | AnyOfCriteria<TQuery>\n | NotCriteria<TQuery>\n | TQuery;\n\n/**\n * An individual request sent to the permission backend.\n * @public\n */\nexport type EvaluatePermissionRequest = {\n permission: Permission;\n resourceRef?: string;\n};\n\n/**\n * A batch of requests sent to the permission backend.\n * @public\n */\nexport type EvaluatePermissionRequestBatch =\n PermissionMessageBatch<EvaluatePermissionRequest>;\n\n/**\n * An individual response from the permission backend.\n *\n * @remarks\n *\n * This response type is an alias of {@link PolicyDecision} to maintain separation between the\n * {@link @backstage/plugin-permission-node#PermissionPolicy} interface and the permission backend\n * api. They may diverge at some point in the future. The response\n *\n * @public\n */\nexport type EvaluatePermissionResponse = PolicyDecision;\n\n/**\n * A batch of responses from the permission backend.\n * @public\n */\nexport type EvaluatePermissionResponseBatch =\n PermissionMessageBatch<EvaluatePermissionResponse>;\n\n/**\n * Request object for {@link PermissionEvaluator.authorize}. If a {@link ResourcePermission}\n * is provided, it must include a corresponding `resourceRef`.\n * @public\n */\nexport type AuthorizePermissionRequest =\n | {\n permission: Exclude<Permission, ResourcePermission>;\n resourceRef?: never;\n }\n | { permission: ResourcePermission; resourceRef: string };\n\n/**\n * Response object for {@link PermissionEvaluator.authorize}.\n * @public\n */\nexport type AuthorizePermissionResponse = DefinitivePolicyDecision;\n\n/**\n * Request object for {@link PermissionEvaluator.authorizeConditional}.\n * @public\n */\nexport type QueryPermissionRequest = {\n permission: ResourcePermission;\n resourceRef?: never;\n};\n\n/**\n * Response object for {@link PermissionEvaluator.authorizeConditional}.\n * @public\n */\nexport type QueryPermissionResponse = PolicyDecision;\n\n/**\n * A client interacting with the permission backend can implement this evaluator interface.\n *\n * @public\n */\nexport interface PermissionEvaluator {\n /**\n * Evaluates {@link Permission | Permissions} and returns a definitive decision.\n */\n authorize(\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]>;\n\n /**\n * Evaluates {@link ResourcePermission | ResourcePermissions} and returns both definitive and\n * conditional decisions, depending on the configured\n * {@link @backstage/plugin-permission-node#PermissionPolicy}. This method is useful when the\n * caller needs more control over the processing of conditional decisions. For example, a plugin\n * backend may want to use {@link PermissionCriteria | conditions} in a database query instead of\n * evaluating each resource in memory.\n */\n authorizeConditional(\n requests: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<QueryPermissionResponse[]>;\n}\n\n/**\n * Options for {@link PermissionEvaluator} requests.\n * The Backstage identity token should be defined if available.\n * @public\n */\nexport type EvaluatorRequestOptions = {\n token?: string;\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 AuthorizePermissionRequest,\n AuthorizePermissionResponse,\n DefinitivePolicyDecision,\n EvaluatorRequestOptions,\n Permission,\n PermissionAuthorizer,\n PermissionEvaluator,\n QueryPermissionRequest,\n QueryPermissionResponse,\n ResourcePermission,\n} from '../types';\n\n/**\n * Check if the two parameters are equivalent permissions.\n * @public\n */\nexport function isPermission<T extends Permission>(\n permission: Permission,\n comparedPermission: T,\n): permission is T {\n return permission.name === comparedPermission.name;\n}\n\n/**\n * Check if a given permission is a {@link ResourcePermission}. When\n * `resourceType` is supplied as the second parameter, also checks if\n * the permission has the specified resource type.\n * @public\n */\nexport function isResourcePermission<T extends string = string>(\n permission: Permission,\n resourceType?: T,\n): permission is ResourcePermission<T> {\n if (!('resourceType' in permission)) {\n return false;\n }\n\n return !resourceType || permission.resourceType === resourceType;\n}\n\n/**\n * Check if a given permission is related to a create action.\n * @public\n */\nexport function isCreatePermission(permission: Permission) {\n return permission.attributes.action === 'create';\n}\n\n/**\n * Check if a given permission is related to a read action.\n * @public\n */\nexport function isReadPermission(permission: Permission) {\n return permission.attributes.action === 'read';\n}\n\n/**\n * Check if a given permission is related to an update action.\n * @public\n */\nexport function isUpdatePermission(permission: Permission) {\n return permission.attributes.action === 'update';\n}\n\n/**\n * Check if a given permission is related to a delete action.\n * @public\n */\nexport function isDeletePermission(permission: Permission) {\n return permission.attributes.action === 'delete';\n}\n\n/**\n * Convert {@link PermissionAuthorizer} to {@link PermissionEvaluator}.\n *\n * @public\n */\nexport function toPermissionEvaluator(\n permissionAuthorizer: PermissionAuthorizer,\n): PermissionEvaluator {\n return {\n authorize: async (\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]> => {\n const response = await permissionAuthorizer.authorize(requests, options);\n\n return response as DefinitivePolicyDecision[];\n },\n authorizeConditional(\n requests: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<QueryPermissionResponse[]> {\n const parsedRequests =\n requests as unknown as AuthorizePermissionRequest[];\n return permissionAuthorizer.authorize(parsedRequests, options);\n },\n };\n}\n","/*\n * Copyright 2022 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 BasicPermission,\n Permission,\n PermissionAttributes,\n ResourcePermission,\n} from '../types';\n\n/**\n * Utility function for creating a valid {@link ResourcePermission}, inferring\n * the appropriate type and resource type parameter.\n *\n * @public\n */\nexport function createPermission<TResourceType extends string>(input: {\n name: string;\n attributes: PermissionAttributes;\n resourceType: TResourceType;\n}): ResourcePermission<TResourceType>;\n/**\n * Utility function for creating a valid {@link BasicPermission}.\n *\n * @public\n */\nexport function createPermission(input: {\n name: string;\n attributes: PermissionAttributes;\n}): BasicPermission;\nexport function createPermission({\n name,\n attributes,\n resourceType,\n}: {\n name: string;\n attributes: PermissionAttributes;\n resourceType?: string;\n}): Permission {\n if (resourceType) {\n return {\n type: 'resource',\n name,\n attributes,\n resourceType,\n };\n }\n\n return {\n type: 'basic',\n name,\n attributes,\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 { Config } from '@backstage/config';\nimport { ResponseError } from '@backstage/errors';\nimport fetch from 'cross-fetch';\nimport * as uuid from 'uuid';\nimport { z } from 'zod';\nimport {\n AuthorizeResult,\n PermissionMessageBatch,\n PermissionCriteria,\n PermissionCondition,\n PermissionEvaluator,\n QueryPermissionRequest,\n AuthorizePermissionRequest,\n EvaluatorRequestOptions,\n AuthorizePermissionResponse,\n QueryPermissionResponse,\n} from './types/api';\nimport { DiscoveryApi } from './types/discovery';\nimport { AuthorizeRequestOptions } from './types/permission';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z\n .object({\n rule: z.string(),\n resourceType: z.string(),\n params: z.array(z.unknown()),\n })\n .or(z.object({ anyOf: z.array(permissionCriteriaSchema).nonempty() }))\n .or(z.object({ allOf: z.array(permissionCriteriaSchema).nonempty() }))\n .or(z.object({ not: permissionCriteriaSchema })),\n);\n\nconst authorizePermissionResponseSchema: z.ZodSchema<AuthorizePermissionResponse> =\n z.object({\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n });\n\nconst queryPermissionResponseSchema: z.ZodSchema<QueryPermissionResponse> =\n z.union([\n z.object({\n result: z\n .literal(AuthorizeResult.ALLOW)\n .or(z.literal(AuthorizeResult.DENY)),\n }),\n z.object({\n result: z.literal(AuthorizeResult.CONDITIONAL),\n pluginId: z.string(),\n resourceType: z.string(),\n conditions: permissionCriteriaSchema,\n }),\n ]);\n\nconst responseSchema = <T>(\n itemSchema: z.ZodSchema<T>,\n ids: Set<string>,\n): z.ZodSchema<PermissionMessageBatch<T>> =>\n z.object({\n items: z\n .array(\n z.intersection(\n z.object({\n id: z.string(),\n }),\n itemSchema,\n ),\n )\n .refine(\n items =>\n items.length === ids.size && items.every(({ id }) => ids.has(id)),\n {\n message: 'Items in response do not match request',\n },\n ),\n });\n\n/**\n * An isomorphic client for requesting authorization for Backstage permissions.\n * @public\n */\nexport class PermissionClient implements PermissionEvaluator {\n private readonly enabled: boolean;\n private readonly discovery: DiscoveryApi;\n\n constructor(options: { discovery: DiscoveryApi; config: Config }) {\n this.discovery = options.discovery;\n this.enabled =\n options.config.getOptionalBoolean('permission.enabled') ?? false;\n }\n\n /**\n * {@inheritdoc PermissionEvaluator.authorize}\n */\n async authorize(\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]> {\n return this.makeRequest(\n requests,\n authorizePermissionResponseSchema,\n options,\n );\n }\n\n /**\n * {@inheritdoc PermissionEvaluator.authorizeConditional}\n */\n async authorizeConditional(\n queries: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<QueryPermissionResponse[]> {\n return this.makeRequest(queries, queryPermissionResponseSchema, options);\n }\n\n private async makeRequest<TQuery, TResult>(\n queries: TQuery[],\n itemSchema: z.ZodSchema<TResult>,\n options?: AuthorizeRequestOptions,\n ) {\n if (!this.enabled) {\n return queries.map(_ => ({ result: AuthorizeResult.ALLOW as const }));\n }\n\n const request: PermissionMessageBatch<TQuery> = {\n items: queries.map(query => ({\n id: uuid.v4(),\n ...query,\n })),\n };\n\n const permissionApi = await this.discovery.getBaseUrl('permission');\n const response = await fetch(`${permissionApi}/authorize`, {\n method: 'POST',\n body: JSON.stringify(request),\n headers: {\n ...this.getAuthorizationHeader(options?.token),\n 'content-type': 'application/json',\n },\n });\n if (!response.ok) {\n throw await ResponseError.fromResponse(response);\n }\n\n const responseBody = await response.json();\n\n const parsedResponse = responseSchema(\n itemSchema,\n new Set(request.items.map(({ id }) => id)),\n ).parse(responseBody);\n\n const responsesById = parsedResponse.items.reduce((acc, r) => {\n acc[r.id] = r;\n return acc;\n }, {} as Record<string, z.infer<typeof itemSchema>>);\n\n return request.items.map(query => responsesById[query.id]);\n }\n\n private getAuthorizationHeader(token?: string): Record<string, string> {\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n}\n"],"names":[],"mappings":";;;;;AAAU,IAAC,eAAe,mBAAmB,CAAC,CAAC,gBAAgB,KAAK;AACpE,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AACpC,EAAE,gBAAgB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;AACtC,EAAE,gBAAgB,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC;AAClD,EAAE,OAAO,gBAAgB,CAAC;AAC1B,CAAC,EAAE,eAAe,IAAI,EAAE;;ACLjB,SAAS,YAAY,CAAC,UAAU,EAAE,kBAAkB,EAAE;AAC7D,EAAE,OAAO,UAAU,CAAC,IAAI,KAAK,kBAAkB,CAAC,IAAI,CAAC;AACrD,CAAC;AACM,SAAS,oBAAoB,CAAC,UAAU,EAAE,YAAY,EAAE;AAC/D,EAAE,IAAI,EAAE,cAAc,IAAI,UAAU,CAAC,EAAE;AACvC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH,EAAE,OAAO,CAAC,YAAY,IAAI,UAAU,CAAC,YAAY,KAAK,YAAY,CAAC;AACnE,CAAC;AACM,SAAS,kBAAkB,CAAC,UAAU,EAAE;AAC/C,EAAE,OAAO,UAAU,CAAC,UAAU,CAAC,MAAM,KAAK,QAAQ,CAAC;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O,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AACtH,IAAI,MAAM,aAAa,GAAG,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK;AAClE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;AACpB,MAAM,OAAO,GAAG,CAAC;AACjB,KAAK,EAAE,EAAE,CAAC,CAAC;AACX,IAAI,OAAO,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,KAAK,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;AACjE,GAAG;AACH,EAAE,sBAAsB,CAAC,KAAK,EAAE;AAChC,IAAI,OAAO,KAAK,GAAG,EAAE,aAAa,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC;AAC7D,GAAG;AACH;;;;"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-permission-common",
|
|
3
3
|
"description": "Isomorphic types and client for Backstage permissions and authorization",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"publishConfig": {
|
|
@@ -48,10 +48,10 @@
|
|
|
48
48
|
"zod": "^3.11.6"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
|
-
"@backstage/cli": "^0.
|
|
51
|
+
"@backstage/cli": "^0.17.0",
|
|
52
52
|
"@types/jest": "^26.0.7",
|
|
53
53
|
"msw": "^0.35.0"
|
|
54
54
|
},
|
|
55
|
-
"gitHead": "
|
|
55
|
+
"gitHead": "e0e44c433319711c2fb8b175db411a621f7aaec2",
|
|
56
56
|
"module": "dist/index.esm.js"
|
|
57
57
|
}
|