@backstage/plugin-permission-common 0.7.14-next.0 → 0.8.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 CHANGED
@@ -1,5 +1,28 @@
1
1
  # @backstage/plugin-permission-common
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f4085b8: **BREAKING**: Removed the deprecated and unused `token` option from `EvaluatorRequestOptions`. The `PermissionsClient` now has its own `PermissionClientRequestOptions` type that declares the `token` option instead.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @backstage/config@1.2.0
13
+ - @backstage/errors@1.2.4
14
+ - @backstage/types@1.1.1
15
+
16
+ ## 0.7.14
17
+
18
+ ### Patch Changes
19
+
20
+ - d44a20a: Added additional plugin metadata to `package.json`.
21
+ - Updated dependencies
22
+ - @backstage/config@1.2.0
23
+ - @backstage/errors@1.2.4
24
+ - @backstage/types@1.1.1
25
+
3
26
  ## 0.7.14-next.0
4
27
 
5
28
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"PermissionClient.esm.js","sources":["../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 { 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.record(z.any()).optional(),\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":";;;;;;AAoCA,MAAM,2BAEF,CAAE,CAAA,IAAA;AAAA,EAAK,MACT,EACG,MAAO,CAAA;AAAA,IACN,IAAA,EAAM,EAAE,MAAO,EAAA;AAAA,IACf,YAAA,EAAc,EAAE,MAAO,EAAA;AAAA,IACvB,QAAQ,CAAE,CAAA,MAAA,CAAO,EAAE,GAAI,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AAO,OAAA,GAAA,CAAA;AAAA,KACT,EAAG,EAAgD,CAAA,CAAA;AAEnD,IAAA,OAAO,QAAQ,KAAM,CAAA,GAAA,CAAI,WAAS,aAAc,CAAA,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAAA,GAC3D;AAAA,EAEQ,uBAAuB,KAAwC,EAAA;AACrE,IAAA,OAAO,QAAQ,EAAE,aAAA,EAAe,UAAU,KAAK,CAAA,CAAA,KAAO,EAAC,CAAA;AAAA,GACzD;AACF;;;;"}
1
+ {"version":3,"file":"PermissionClient.esm.js","sources":["../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 { 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 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.record(z.any()).optional(),\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 * Options for {@link PermissionClient} requests.\n *\n * @public\n */\nexport type PermissionClientRequestOptions = {\n token?: string;\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?: PermissionClientRequestOptions,\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?: PermissionClientRequestOptions,\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":";;;;;;AAmCA,MAAM,2BAEF,CAAE,CAAA,IAAA;AAAA,EAAK,MACT,EACG,MAAO,CAAA;AAAA,IACN,IAAA,EAAM,EAAE,MAAO,EAAA;AAAA,IACf,YAAA,EAAc,EAAE,MAAO,EAAA;AAAA,IACvB,QAAQ,CAAE,CAAA,MAAA,CAAO,EAAE,GAAI,EAAC,EAAE,QAAS,EAAA;AAAA,GACpC,CACA,CAAA,EAAA,CAAG,CAAE,CAAA,MAAA,CAAO,EAAE,KAAO,EAAA,CAAA,CAAE,KAAM,CAAA,wBAAwB,EAAE,QAAS,EAAA,EAAG,CAAC,EACpE,EAAG,CAAA,CAAA,CAAE,MAAO,CAAA,EAAE,OAAO,CAAE,CAAA,KAAA,CAAM,wBAAwB,CAAA,CAAE,UAAW,EAAC,CAAC,CAAA,CACpE,GA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A;AAAA,GACzD;AACF;;;;"}
@@ -1 +1 @@
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 { JsonPrimitive } from '@backstage/types';\nimport { Permission, ResourcePermission } 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 PermissionRuleParams = PermissionRuleParams,\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 * A parameter to a permission rule.\n *\n * @public\n */\nexport type PermissionRuleParam = undefined | JsonPrimitive | JsonPrimitive[];\n\n/**\n * Types that can be used as parameters to permission rules.\n *\n * @public\n */\nexport type PermissionRuleParams =\n | undefined\n | Record<string, PermissionRuleParam>;\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 *\n * @public\n */\nexport type EvaluatorRequestOptions = {\n /**\n * @deprecated Backend plugins should no longer depend on the\n * `PermissionEvaluator`, but instead use the `PermissionService` from\n * `@backstage/backend-plugin-api`. Frontend plugins should not need to inject\n * this token at all, but instead implicitly rely on underlying fetchApi to do\n * it for them.\n */\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.record(z.any()).optional(),\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":["AuthorizeResult","z","uuid","fetch","ResponseError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCY,IAAA,eAAA,qBAAAA,gBAAL,KAAA;AAIL,EAAAA,iBAAA,MAAO,CAAA,GAAA,MAAA,CAAA;AAIP,EAAAA,iBAAA,OAAQ,CAAA,GAAA,OAAA,CAAA;AAIR,EAAAA,iBAAA,aAAc,CAAA,GAAA,aAAA,CAAA;AAZJ,EAAAA,OAAAA,gBAAAA,CAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;ACLI,SAAA,YAAA,CACd,YACA,kBACiB,EAAA;AACjB,EAAO,OAAA,UAAA,CAAW,SAAS,kBAAmB,CAAA,IAAA,CAAA;AAChD,CAAA;AAQgB,SAAA,oBAAA,CACd,YACA,YACqC,EAAA;AACrC,EAAI,IAAA,EAAE,kBAAkB,UAAa,CAAA,EAAA;AACnC,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AAEA,EAAO,OAAA,CAAC,YAAgB,IAAA,UAAA,CAAW,YAAiB,KAAA,YAAA,CAAA;AACtD,CAAA;AAMO,SAAS,mBAAmB,UAAwB,EAAA;AACzD,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AY,CAAA,CAAA;AAEpB,IAAA,MAAM,gBAAgB,cAAe,CAAA,KAAA,CAAM,MAAO,CAAA,CAAC,KAAK,CAAM,KAAA;AAC5D,MAAI,GAAA,CAAA,CAAA,CAAE,EAAE,CAAI,GAAA,CAAA,CAAA;AACZ,MAAO,OAAA,GAAA,CAAA;AAAA,KACT,EAAG,EAAgD,CAAA,CAAA;AAEnD,IAAA,OAAO,QAAQ,KAAM,CAAA,GAAA,CAAI,WAAS,aAAc,CAAA,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAAA,GAC3D;AAAA,EAEQ,uBAAuB,KAAwC,EAAA;AACrE,IAAA,OAAO,QAAQ,EAAE,aAAA,EAAe,UAAU,KAAK,CAAA,CAAA,KAAO,EAAC,CAAA;AAAA,GACzD;AACF;;;;;;;;;;;;;"}
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 { JsonPrimitive } from '@backstage/types';\nimport { Permission, ResourcePermission } 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 PermissionRuleParams = PermissionRuleParams,\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 * A parameter to a permission rule.\n *\n * @public\n */\nexport type PermissionRuleParam = undefined | JsonPrimitive | JsonPrimitive[];\n\n/**\n * Types that can be used as parameters to permission rules.\n *\n * @public\n */\nexport type PermissionRuleParams =\n | undefined\n | Record<string, PermissionRuleParam>;\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 & { _ignored?: never }, // Since the options are empty we add this placeholder to reject all options\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 & { _ignored?: never }, // Since the options are empty we add this placeholder to reject all options\n ): Promise<QueryPermissionResponse[]>;\n}\n\n// Note(Rugvip): I kept the below type around in case we want to add new options\n// in the future, for example a signal. It also helps out enabling API\n// constraints, as without this we can't have the permissions service implement\n// the evaluator interface due to the mismatch in parameter count.\n\n/**\n * Options for {@link PermissionEvaluator} requests.\n *\n * This is currently empty, as there are no longer any common options for the permission evaluator.\n *\n * @public\n */\nexport interface EvaluatorRequestOptions {}\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 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.record(z.any()).optional(),\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 * Options for {@link PermissionClient} requests.\n *\n * @public\n */\nexport type PermissionClientRequestOptions = {\n token?: string;\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?: PermissionClientRequestOptions,\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?: PermissionClientRequestOptions,\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":["AuthorizeResult","z","uuid","fetch","ResponseError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCY,IAAA,eAAA,qBAAAA,gBAAL,KAAA;AAIL,EA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AA,EAAM,IAAK,CAAA,SAAA,CAAU,OAAO,CAAA;AAAA,MAC5B,OAAS,EAAA;AAAA,QACP,GAAG,IAAA,CAAK,sBAAuB,CAAA,OAAA,EAAS,KAAK,CAAA;AAAA,QAC7C,cAAgB,EAAA,kBAAA;AAAA,OAClB;AAAA,KACD,CAAA,CAAA;AACD,IAAI,IAAA,CAAC,SAAS,EAAI,EAAA;AAChB,MAAM,MAAA,MAAMC,oBAAc,CAAA,YAAA,CAAa,QAAQ,CAAA,CAAA;AAAA,KACjD;AAEA,IAAM,MAAA,YAAA,GAAe,MAAM,QAAA,CAAS,IAAK,EAAA,CAAA;AAEzC,IAAA,MAAM,cAAiB,GAAA,cAAA;AAAA,MACrB,UAAA;AAAA,MACA,IAAI,GAAI,CAAA,OAAA,CAAQ,KAAM,CAAA,GAAA,CAAI,CAAC,EAAE,EAAA,EAAS,KAAA,EAAE,CAAC,CAAA;AAAA,KAC3C,CAAE,MAAM,YAAY,CAAA,CAAA;AAEpB,IAAA,MAAM,gBAAgB,cAAe,CAAA,KAAA,CAAM,MAAO,CAAA,CAAC,KAAK,CAAM,KAAA;AAC5D,MAAI,GAAA,CAAA,CAAA,CAAE,EAAE,CAAI,GAAA,CAAA,CAAA;AACZ,MAAO,OAAA,GAAA,CAAA;AAAA,KACT,EAAG,EAAgD,CAAA,CAAA;AAEnD,IAAA,OAAO,QAAQ,KAAM,CAAA,GAAA,CAAI,WAAS,aAAc,CAAA,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAAA,GAC3D;AAAA,EAEQ,uBAAuB,KAAwC,EAAA;AACrE,IAAA,OAAO,QAAQ,EAAE,aAAA,EAAe,UAAU,KAAK,CAAA,CAAA,KAAO,EAAC,CAAA;AAAA,GACzD;AACF;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -273,7 +273,9 @@ interface PermissionEvaluator {
273
273
  /**
274
274
  * Evaluates {@link Permission | Permissions} and returns a definitive decision.
275
275
  */
276
- authorize(requests: AuthorizePermissionRequest[], options?: EvaluatorRequestOptions): Promise<AuthorizePermissionResponse[]>;
276
+ authorize(requests: AuthorizePermissionRequest[], options?: EvaluatorRequestOptions & {
277
+ _ignored?: never;
278
+ }): Promise<AuthorizePermissionResponse[]>;
277
279
  /**
278
280
  * Evaluates {@link ResourcePermission | ResourcePermissions} and returns both definitive and
279
281
  * conditional decisions, depending on the configured
@@ -282,23 +284,19 @@ interface PermissionEvaluator {
282
284
  * backend may want to use {@link PermissionCriteria | conditions} in a database query instead of
283
285
  * evaluating each resource in memory.
284
286
  */
285
- authorizeConditional(requests: QueryPermissionRequest[], options?: EvaluatorRequestOptions): Promise<QueryPermissionResponse[]>;
287
+ authorizeConditional(requests: QueryPermissionRequest[], options?: EvaluatorRequestOptions & {
288
+ _ignored?: never;
289
+ }): Promise<QueryPermissionResponse[]>;
286
290
  }
287
291
  /**
288
292
  * Options for {@link PermissionEvaluator} requests.
289
293
  *
294
+ * This is currently empty, as there are no longer any common options for the permission evaluator.
295
+ *
290
296
  * @public
291
297
  */
292
- type EvaluatorRequestOptions = {
293
- /**
294
- * @deprecated Backend plugins should no longer depend on the
295
- * `PermissionEvaluator`, but instead use the `PermissionService` from
296
- * `@backstage/backend-plugin-api`. Frontend plugins should not need to inject
297
- * this token at all, but instead implicitly rely on underlying fetchApi to do
298
- * it for them.
299
- */
300
- token?: string;
301
- };
298
+ interface EvaluatorRequestOptions {
299
+ }
302
300
 
303
301
  /**
304
302
  * This is a copy of the core DiscoveryApi, to avoid importing core.
@@ -369,6 +367,14 @@ declare function createPermission(input: {
369
367
  attributes: PermissionAttributes;
370
368
  }): BasicPermission;
371
369
 
370
+ /**
371
+ * Options for {@link PermissionClient} requests.
372
+ *
373
+ * @public
374
+ */
375
+ type PermissionClientRequestOptions = {
376
+ token?: string;
377
+ };
372
378
  /**
373
379
  * An isomorphic client for requesting authorization for Backstage permissions.
374
380
  * @public
@@ -383,13 +389,13 @@ declare class PermissionClient implements PermissionEvaluator {
383
389
  /**
384
390
  * {@inheritdoc PermissionEvaluator.authorize}
385
391
  */
386
- authorize(requests: AuthorizePermissionRequest[], options?: EvaluatorRequestOptions): Promise<AuthorizePermissionResponse[]>;
392
+ authorize(requests: AuthorizePermissionRequest[], options?: PermissionClientRequestOptions): Promise<AuthorizePermissionResponse[]>;
387
393
  /**
388
394
  * {@inheritdoc PermissionEvaluator.authorizeConditional}
389
395
  */
390
- authorizeConditional(queries: QueryPermissionRequest[], options?: EvaluatorRequestOptions): Promise<QueryPermissionResponse[]>;
396
+ authorizeConditional(queries: QueryPermissionRequest[], options?: PermissionClientRequestOptions): Promise<QueryPermissionResponse[]>;
391
397
  private makeRequest;
392
398
  private getAuthorizationHeader;
393
399
  }
394
400
 
395
- export { type AllOfCriteria, type AnyOfCriteria, type AuthorizePermissionRequest, type AuthorizePermissionResponse, type AuthorizeRequestOptions, AuthorizeResult, type BasicPermission, type ConditionalPolicyDecision, type DefinitivePolicyDecision, type DiscoveryApi, type EvaluatePermissionRequest, type EvaluatePermissionRequestBatch, type EvaluatePermissionResponse, type EvaluatePermissionResponseBatch, type EvaluatorRequestOptions, type IdentifiedPermissionMessage, type NotCriteria, type Permission, type PermissionAttributes, type PermissionAuthorizer, type PermissionBase, PermissionClient, type PermissionCondition, type PermissionCriteria, type PermissionEvaluator, type PermissionMessageBatch, type PermissionRuleParam, type PermissionRuleParams, type PolicyDecision, type QueryPermissionRequest, type QueryPermissionResponse, type ResourcePermission, createPermission, isCreatePermission, isDeletePermission, isPermission, isReadPermission, isResourcePermission, isUpdatePermission, toPermissionEvaluator };
401
+ export { type AllOfCriteria, type AnyOfCriteria, type AuthorizePermissionRequest, type AuthorizePermissionResponse, type AuthorizeRequestOptions, AuthorizeResult, type BasicPermission, type ConditionalPolicyDecision, type DefinitivePolicyDecision, type DiscoveryApi, type EvaluatePermissionRequest, type EvaluatePermissionRequestBatch, type EvaluatePermissionResponse, type EvaluatePermissionResponseBatch, type EvaluatorRequestOptions, type IdentifiedPermissionMessage, type NotCriteria, type Permission, type PermissionAttributes, type PermissionAuthorizer, type PermissionBase, PermissionClient, type PermissionClientRequestOptions, type PermissionCondition, type PermissionCriteria, type PermissionEvaluator, type PermissionMessageBatch, type PermissionRuleParam, type PermissionRuleParams, type PolicyDecision, type QueryPermissionRequest, type QueryPermissionResponse, type ResourcePermission, createPermission, isCreatePermission, isDeletePermission, isPermission, isReadPermission, isResourcePermission, isUpdatePermission, toPermissionEvaluator };
@@ -1 +1 @@
1
- {"version":3,"file":"api.esm.js","sources":["../../src/types/api.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 { JsonPrimitive } from '@backstage/types';\nimport { Permission, ResourcePermission } 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 PermissionRuleParams = PermissionRuleParams,\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 * A parameter to a permission rule.\n *\n * @public\n */\nexport type PermissionRuleParam = undefined | JsonPrimitive | JsonPrimitive[];\n\n/**\n * Types that can be used as parameters to permission rules.\n *\n * @public\n */\nexport type PermissionRuleParams =\n | undefined\n | Record<string, PermissionRuleParam>;\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 *\n * @public\n */\nexport type EvaluatorRequestOptions = {\n /**\n * @deprecated Backend plugins should no longer depend on the\n * `PermissionEvaluator`, but instead use the `PermissionService` from\n * `@backstage/backend-plugin-api`. Frontend plugins should not need to inject\n * this token at all, but instead implicitly rely on underlying fetchApi to do\n * it for them.\n */\n token?: string;\n};\n"],"names":["AuthorizeResult"],"mappings":"AAsCY,IAAA,eAAA,qBAAAA,gBAAL,KAAA;AAIL,EAAAA,iBAAA,MAAO,CAAA,GAAA,MAAA,CAAA;AAIP,EAAAA,iBAAA,OAAQ,CAAA,GAAA,OAAA,CAAA;AAIR,EAAAA,iBAAA,aAAc,CAAA,GAAA,aAAA,CAAA;AAZJ,EAAAA,OAAAA,gBAAAA,CAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;;;"}
1
+ {"version":3,"file":"api.esm.js","sources":["../../src/types/api.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 { JsonPrimitive } from '@backstage/types';\nimport { Permission, ResourcePermission } 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 PermissionRuleParams = PermissionRuleParams,\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 * A parameter to a permission rule.\n *\n * @public\n */\nexport type PermissionRuleParam = undefined | JsonPrimitive | JsonPrimitive[];\n\n/**\n * Types that can be used as parameters to permission rules.\n *\n * @public\n */\nexport type PermissionRuleParams =\n | undefined\n | Record<string, PermissionRuleParam>;\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 & { _ignored?: never }, // Since the options are empty we add this placeholder to reject all options\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 & { _ignored?: never }, // Since the options are empty we add this placeholder to reject all options\n ): Promise<QueryPermissionResponse[]>;\n}\n\n// Note(Rugvip): I kept the below type around in case we want to add new options\n// in the future, for example a signal. It also helps out enabling API\n// constraints, as without this we can't have the permissions service implement\n// the evaluator interface due to the mismatch in parameter count.\n\n/**\n * Options for {@link PermissionEvaluator} requests.\n *\n * This is currently empty, as there are no longer any common options for the permission evaluator.\n *\n * @public\n */\nexport interface EvaluatorRequestOptions {}\n"],"names":["AuthorizeResult"],"mappings":"AAsCY,IAAA,eAAA,qBAAAA,gBAAL,KAAA;AAIL,EAAAA,iBAAA,MAAO,CAAA,GAAA,MAAA,CAAA;AAIP,EAAAA,iBAAA,OAAQ,CAAA,GAAA,OAAA,CAAA;AAIR,EAAAA,iBAAA,aAAc,CAAA,GAAA,aAAA,CAAA;AAZJ,EAAAA,OAAAA,gBAAAA,CAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-permission-common",
3
- "version": "0.7.14-next.0",
3
+ "version": "0.8.0",
4
4
  "description": "Isomorphic types and client for Backstage permissions and authorization",
5
5
  "backstage": {
6
6
  "role": "common-library",
@@ -56,7 +56,7 @@
56
56
  "zod": "^3.22.4"
57
57
  },
58
58
  "devDependencies": {
59
- "@backstage/cli": "^0.26.7-next.3",
59
+ "@backstage/cli": "^0.26.11",
60
60
  "msw": "^1.0.0"
61
61
  },
62
62
  "configSchema": "config.d.ts",