@backstage/plugin-permission-common 0.5.2 → 0.6.0-next.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 CHANGED
@@ -1,5 +1,46 @@
1
1
  # @backstage/plugin-permission-common
2
2
 
3
+ ## 0.6.0-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 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:
8
+
9
+ - `authorize()`: Used when the caller requires a definitive decision.
10
+ - `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.
11
+
12
+ ## 0.6.0-next.0
13
+
14
+ ### Minor Changes
15
+
16
+ - 8012ac46a0: Add `resourceType` property to `PermissionCondition` type to allow matching them with `ResourcePermission` instances.
17
+ - c98d271466: Refactor api types into more specific, decoupled names.
18
+
19
+ - **BREAKING:**
20
+ - Renamed `AuthorizeDecision` to `EvaluatePermissionResponse`
21
+ - Renamed `AuthorizeQuery` to `EvaluatePermissionRequest`
22
+ - Renamed `AuthorizeRequest` to `EvaluatePermissionRequestBatch`
23
+ - Renamed `AuthorizeResponse` to `EvaluatePermissionResponseBatch`
24
+ - Renamed `Identified` to `IdentifiedPermissionMessage`
25
+ - Add `PermissionMessageBatch` helper type
26
+ - Add `ConditionalPolicyDecision`, `DefinitivePolicyDecision`, and `PolicyDecision` types from `@backstage/plugin-permission-node`
27
+
28
+ ### Patch Changes
29
+
30
+ - 8012ac46a0: Add `isPermission` helper method.
31
+ - 95284162d6: - Add more specific `Permission` types.
32
+ - Add `createPermission` helper to infer the appropriate type for some permission input.
33
+ - Add `isResourcePermission` helper to refine Permissions to ResourcePermissions.
34
+
35
+ ## 0.5.3
36
+
37
+ ### Patch Changes
38
+
39
+ - f24ef7864e: Minor typo fixes
40
+ - Updated dependencies
41
+ - @backstage/config@1.0.0
42
+ - @backstage/errors@1.0.0
43
+
3
44
  ## 0.5.2
4
45
 
5
46
  ### 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
98
  }).strict().or(zod.z.object({ anyOf: zod.z.array(permissionCriteriaSchema).nonempty() }).strict()).or(zod.z.object({ allOf: zod.z.array(permissionCriteriaSchema).nonempty() }).strict()).or(zod.z.object({ not: permissionCriteriaSchema }).strict()));
57
- const responseSchema = zod.z.object({
58
- items: zod.z.array(zod.z.object({
59
- id: zod.z.string(),
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
- }).or(zod.z.object({
62
- id: zod.z.string(),
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(queries, options) {
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
- this.assertValidResponse(request, responseBody);
97
- const responsesById = responseBody.items.reduce((acc, r) => {
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
@@ -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 * Represnts a logical AND for the provided criteria.\n * @public\n */\nexport type AllOfCriteria<TQuery> = {\n allOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represnts 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6BY,oCAAA,qBAAL;AAIL,6BAAO;AAIP,8BAAQ;AAIR,oCAAc;AAZJ;AAAA;;4BCPuB,YAAwB;AACzD,SAAO,WAAW,WAAW,WAAW;AAAA;0BAOT,YAAwB;AACvD,SAAO,WAAW,WAAW,WAAW;AAAA;4BAOP,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S;AAAA,QACxC,gBAAgB;AAAA;AAAA;AAGpB,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,MAAMC,qBAAc,aAAa;AAAA;AAGzC,UAAM,eAAe,MAAM,SAAS;AACpC,SAAK,oBAAoB,SAAS;AAElC,UAAM,gBAAgB,aAAa,MAAM,OAAO,CAAC,KAAK,MAAM;AAC1D,UAAI,EAAE,MAAM;AACZ,aAAO;AAAA,OACN;AAEH,WAAO,QAAQ,MAAM,IAAI,WAAS,cAAc,MAAM;AAAA;AAAA,EAGhD,uBAAuB,OAAwC;AACrE,WAAO,QAAQ,EAAE,eAAe,UAAU,YAAY;AAAA;AAAA,EAGhD,oBACN,SACA,MACmC;AACnC,UAAM,sBAAsB,eAAe,MAAM;AACjD,UAAM,cAAc,oBAAoB,MAAM,IAAI,OAAK,EAAE;AACzD,UAAM,mBAAmB,QAAQ,MAAM,MAAM,OAC3C,YAAY,SAAS,EAAE;AAEzB,QAAI,CAAC,kBAAkB;AACrB,YAAM,IAAI,MACR;AAAA;AAAA;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 .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 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,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 +9,10 @@ declare type PermissionAttributes = {
9
9
  action?: 'create' | 'read' | 'update' | 'delete';
10
10
  };
11
11
  /**
12
- * A permission that can be checked through authorization.
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 Permission = {
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
- * Some permissions can be authorized based on characteristics of a resource
35
- * such a catalog entity. For these permissions, the resourceType field
36
- * denotes the type of the resource whose resourceRef should be passed when
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?: string;
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(queries: AuthorizeQuery[], options?: AuthorizeRequestOptions): Promise<AuthorizeDecision[]>;
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 Identified<T> = T & {
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
- * An individual authorization request for {@link PermissionClient#authorize}.
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 AuthorizeQuery = {
87
- permission: Permission;
88
- resourceRef?: string;
124
+ declare type DefinitivePolicyDecision = {
125
+ result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;
89
126
  };
90
127
  /**
91
- * A batch of authorization requests from {@link PermissionClient#authorize}.
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 AuthorizeRequest = {
95
- items: Identified<AuthorizeQuery>[];
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
  };
@@ -112,14 +166,14 @@ declare type PermissionCondition<TParams extends unknown[] = unknown[]> = {
112
166
  */
113
167
  declare type NonEmptyArray<T> = [T, ...T[]];
114
168
  /**
115
- * Represnts a logical AND for the provided criteria.
169
+ * Represents a logical AND for the provided criteria.
116
170
  * @public
117
171
  */
118
172
  declare type AllOfCriteria<TQuery> = {
119
173
  allOf: NonEmptyArray<PermissionCriteria<TQuery>>;
120
174
  };
121
175
  /**
122
- * Represnts a logical OR for the provided criteria.
176
+ * Represents a logical OR for the provided criteria.
123
177
  * @public
124
178
  */
125
179
  declare type AnyOfCriteria<TQuery> = {
@@ -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 authorization response from {@link PermissionClient#authorize}.
195
+ * An individual request sent to the permission backend.
142
196
  * @public
143
197
  */
144
- declare type AuthorizeDecision = {
145
- result: AuthorizeResult.ALLOW | AuthorizeResult.DENY;
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
- result: AuthorizeResult.CONDITIONAL;
148
- conditions: PermissionCriteria<PermissionCondition>;
233
+ permission: ResourcePermission;
234
+ resourceRef: string;
149
235
  };
150
236
  /**
151
- * A batch of authorization responses from {@link PermissionClient#authorize}.
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 AuthorizeResponse = {
155
- items: Identified<AuthorizeDecision>[];
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 PermissionAuthorizer {
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
- * Request authorization from the permission-backend for the given set of permissions.
201
- *
202
- * Authorization requests check that a given Backstage user can perform a protected operation,
203
- * potentially for a specific resource (such as a catalog entity). The Backstage identity token
204
- * should be included in the `options` if available.
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
- authorize(queries: AuthorizeQuery[], options?: AuthorizeRequestOptions): Promise<AuthorizeDecision[]>;
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, AuthorizeDecision, AuthorizeQuery, AuthorizeRequest, AuthorizeRequestOptions, AuthorizeResponse, AuthorizeResult, DiscoveryApi, Identified, NotCriteria, Permission, PermissionAttributes, PermissionAuthorizer, PermissionClient, PermissionCondition, PermissionCriteria, isCreatePermission, isDeletePermission, isReadPermission, isUpdatePermission };
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
71
  }).strict().or(z.object({ anyOf: z.array(permissionCriteriaSchema).nonempty() }).strict()).or(z.object({ allOf: z.array(permissionCriteriaSchema).nonempty() }).strict()).or(z.object({ not: permissionCriteriaSchema }).strict()));
30
- const responseSchema = z.object({
31
- items: z.array(z.object({
32
- id: z.string(),
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
- }).or(z.object({
35
- id: z.string(),
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(queries, options) {
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
- this.assertValidResponse(request, responseBody);
70
- const responsesById = responseBody.items.reduce((acc, r) => {
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
@@ -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 * Represnts a logical AND for the provided criteria.\n * @public\n */\nexport type AllOfCriteria<TQuery> = {\n allOf: NonEmptyArray<PermissionCriteria<TQuery>>;\n};\n\n/**\n * Represnts 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":";;;;;IA6BY,oCAAA,qBAAL;AAIL,6BAAO;AAIP,8BAAQ;AAIR,oCAAc;AAZJ;AAAA;;4BCPuB,YAAwB;AACzD,SAAO,WAAW,WAAW,WAAW;AAAA;0BAOT,YAAwB;AACvD,SAAO,WAAW,WAAW,WAAW;AAAA;4BAOP,YAAwB;AACzD,SAAO,WAAW,WAAW,WAAW;AAAA;4BAOP,YAAwB;AACzD,SAAO,WAAW,WAAW,WAAW;AAAA;;ACV1C,MAAM,2BAEF,EAAE,KAAK,MACT,EACG,OAAO;AAAA,EACN,MAAM,EAAE;AAAA,EACR,QAAQ,EAAE,MAAM,EAAE;AAAA,GAEnB,SACA,GACC,EACG,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,cAClD,UAEJ,GACC,EACG,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,cAClD,UAEJ,GAAG,EAAE,OAAO,EAAE,KAAK,4BAA4B;AAGpD,MAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,OAAO,EAAE,MACP,EACG,OAAO;AAAA,IACN,IAAI,EAAE;AAAA,IACN,QAAQ,EACL,QAAQ,gBAAgB,OACxB,GAAG,EAAE,QAAQ,gBAAgB;AAAA,KAEjC,GACC,EAAE,OAAO;A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rB,YAAM,IAAI,MACR;AAAA;AAAA;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 .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 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;AACnD,CAAC;AACM,SAAS,gBAAgB,CAAC,UAAU,EAAE;AAC7C,EAAE,OAAO,UAAU,CAAC,UAAU,CAAC,MAAM,KAAK,MAAM,CAAC;AACjD,CAAC;AACM,SAAS,kBAAkB,CAAC,UAAU,EAAE;AAC/C,EAAE,OAAO,UAAU,CAAC,UAAU,CAAC,MAAM,KAAK,QAAQ,C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,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.5.2",
4
+ "version": "0.6.0-next.1",
5
5
  "main": "dist/index.cjs.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "publishConfig": {
@@ -41,17 +41,17 @@
41
41
  "url": "https://github.com/backstage/backstage/issues"
42
42
  },
43
43
  "dependencies": {
44
- "@backstage/config": "^0.1.15",
45
- "@backstage/errors": "^0.2.2",
44
+ "@backstage/config": "^1.0.0",
45
+ "@backstage/errors": "^1.0.0",
46
46
  "cross-fetch": "^3.1.5",
47
47
  "uuid": "^8.0.0",
48
48
  "zod": "^3.11.6"
49
49
  },
50
50
  "devDependencies": {
51
- "@backstage/cli": "^0.15.0",
51
+ "@backstage/cli": "^0.17.0-next.3",
52
52
  "@types/jest": "^26.0.7",
53
53
  "msw": "^0.35.0"
54
54
  },
55
- "gitHead": "04bb0dd824b78f6b57dac62c3015e681f094045c",
55
+ "gitHead": "2eca57d93ef1081f4a76a19fc994a8e9e1a19e00",
56
56
  "module": "dist/index.esm.js"
57
57
  }