@backstage/plugin-permission-node 0.7.24 → 0.7.25-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,31 +1,29 @@
1
1
  # @backstage/plugin-permission-node
2
2
 
3
- ## 0.7.24
3
+ ## 0.7.25-next.1
4
4
 
5
5
  ### Patch Changes
6
6
 
7
7
  - Updated dependencies
8
- - @backstage/backend-common@0.21.3
9
- - @backstage/plugin-auth-node@0.4.8
10
- - @backstage/backend-plugin-api@0.6.13
8
+ - @backstage/config@1.2.0-next.1
9
+ - @backstage/backend-common@0.21.4-next.1
10
+ - @backstage/backend-plugin-api@0.6.14-next.1
11
+ - @backstage/plugin-auth-node@0.4.9-next.1
12
+ - @backstage/plugin-permission-common@0.7.13-next.1
13
+ - @backstage/errors@1.2.4-next.0
11
14
 
12
- ## 0.7.23
15
+ ## 0.7.24-next.0
13
16
 
14
17
  ### Patch Changes
15
18
 
19
+ - 0502d82: The `ServerPermissionClient` has been migrated to implement the `PermissionsService` interface, now accepting the new `BackstageCredentials` object in addition to the `token` option, which is now deprecated. It now also optionally depends on the new `AuthService`.
16
20
  - Updated dependencies
17
- - @backstage/backend-common@0.21.2
18
- - @backstage/plugin-auth-node@0.4.7
19
- - @backstage/backend-plugin-api@0.6.12
20
-
21
- ## 0.7.22
22
-
23
- ### Patch Changes
24
-
25
- - Updated dependencies
26
- - @backstage/backend-common@0.21.1
27
- - @backstage/plugin-auth-node@0.4.6
28
- - @backstage/backend-plugin-api@0.6.11
21
+ - @backstage/backend-common@0.21.3-next.0
22
+ - @backstage/plugin-auth-node@0.4.8-next.0
23
+ - @backstage/errors@1.2.4-next.0
24
+ - @backstage/backend-plugin-api@0.6.13-next.0
25
+ - @backstage/plugin-permission-common@0.7.13-next.0
26
+ - @backstage/config@1.1.2-next.0
29
27
 
30
28
  ## 0.7.21
31
29
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-permission-node",
3
- "version": "0.7.24",
3
+ "version": "0.7.25-next.1",
4
4
  "main": "../dist/alpha.cjs.js",
5
5
  "types": "../dist/alpha.d.ts"
6
6
  }
package/dist/index.cjs.js CHANGED
@@ -259,20 +259,39 @@ function isCreatePermissionIntegrationRouterResourceOptions(options) {
259
259
  const createPermissionRule = (rule) => rule;
260
260
  const makeCreatePermissionRule = () => (rule) => createPermissionRule(rule);
261
261
 
262
- var __defProp = Object.defineProperty;
263
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
264
- var __publicField = (obj, key, value) => {
265
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
262
+ var __accessCheck = (obj, member, msg) => {
263
+ if (!member.has(obj))
264
+ throw TypeError("Cannot " + msg);
265
+ };
266
+ var __privateGet = (obj, member, getter) => {
267
+ __accessCheck(obj, member, "read from private field");
268
+ return getter ? getter.call(obj) : member.get(obj);
269
+ };
270
+ var __privateAdd = (obj, member, value) => {
271
+ if (member.has(obj))
272
+ throw TypeError("Cannot add the same private member more than once");
273
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
274
+ };
275
+ var __privateSet = (obj, member, value, setter) => {
276
+ __accessCheck(obj, member, "write to private field");
277
+ setter ? setter.call(obj, value) : member.set(obj, value);
266
278
  return value;
267
279
  };
268
- class ServerPermissionClient {
280
+ var __privateMethod = (obj, member, method) => {
281
+ __accessCheck(obj, member, "access private method");
282
+ return method;
283
+ };
284
+ var _auth, _permissionClient, _permissionEnabled, _getRequestOptions, getRequestOptions_fn, _shouldPermissionsBeApplied, shouldPermissionsBeApplied_fn;
285
+ const _ServerPermissionClient = class _ServerPermissionClient {
269
286
  constructor(options) {
270
- __publicField(this, "permissionClient");
271
- __publicField(this, "tokenManager");
272
- __publicField(this, "permissionEnabled");
273
- this.permissionClient = options.permissionClient;
274
- this.tokenManager = options.tokenManager;
275
- this.permissionEnabled = options.permissionEnabled;
287
+ __privateAdd(this, _getRequestOptions);
288
+ __privateAdd(this, _shouldPermissionsBeApplied);
289
+ __privateAdd(this, _auth, void 0);
290
+ __privateAdd(this, _permissionClient, void 0);
291
+ __privateAdd(this, _permissionEnabled, void 0);
292
+ __privateSet(this, _auth, options.auth);
293
+ __privateSet(this, _permissionClient, options.permissionClient);
294
+ __privateSet(this, _permissionEnabled, options.permissionEnabled);
276
295
  }
277
296
  static fromConfig(config, options) {
278
297
  var _a;
@@ -284,28 +303,72 @@ class ServerPermissionClient {
284
303
  "Service-to-service authentication must be configured before enabling permissions. Read more here https://backstage.io/docs/auth/service-to-service-auth"
285
304
  );
286
305
  }
287
- return new ServerPermissionClient({
306
+ const { auth } = backendCommon.createLegacyAuthAdapters(options);
307
+ return new _ServerPermissionClient({
308
+ auth,
288
309
  permissionClient,
289
- tokenManager,
290
310
  permissionEnabled
291
311
  });
292
312
  }
293
313
  async authorizeConditional(queries, options) {
294
- return await this.isEnabled(options == null ? void 0 : options.token) ? this.permissionClient.authorizeConditional(queries, options) : queries.map((_) => ({ result: pluginPermissionCommon.AuthorizeResult.ALLOW }));
314
+ if (await __privateMethod(this, _shouldPermissionsBeApplied, shouldPermissionsBeApplied_fn).call(this, options)) {
315
+ return __privateGet(this, _permissionClient).authorizeConditional(
316
+ queries,
317
+ await __privateMethod(this, _getRequestOptions, getRequestOptions_fn).call(this, options)
318
+ );
319
+ }
320
+ return queries.map((_) => ({ result: pluginPermissionCommon.AuthorizeResult.ALLOW }));
295
321
  }
296
322
  async authorize(requests, options) {
297
- return await this.isEnabled(options == null ? void 0 : options.token) ? this.permissionClient.authorize(requests, options) : requests.map((_) => ({ result: pluginPermissionCommon.AuthorizeResult.ALLOW }));
323
+ if (await __privateMethod(this, _shouldPermissionsBeApplied, shouldPermissionsBeApplied_fn).call(this, options)) {
324
+ return __privateGet(this, _permissionClient).authorize(
325
+ requests,
326
+ await __privateMethod(this, _getRequestOptions, getRequestOptions_fn).call(this, options)
327
+ );
328
+ }
329
+ return requests.map((_) => ({ result: pluginPermissionCommon.AuthorizeResult.ALLOW }));
298
330
  }
299
- async isValidServerToken(token) {
300
- if (!token) {
301
- return false;
331
+ };
332
+ _auth = new WeakMap();
333
+ _permissionClient = new WeakMap();
334
+ _permissionEnabled = new WeakMap();
335
+ _getRequestOptions = new WeakSet();
336
+ getRequestOptions_fn = async function(options) {
337
+ if (options && "credentials" in options) {
338
+ if (__privateGet(this, _auth).isPrincipal(options.credentials, "none")) {
339
+ return {};
302
340
  }
303
- return this.tokenManager.authenticate(token).then(() => true).catch(() => false);
341
+ return __privateGet(this, _auth).getPluginRequestToken({
342
+ onBehalfOf: options.credentials,
343
+ targetPluginId: "permissions"
344
+ });
304
345
  }
305
- async isEnabled(token) {
306
- return this.permissionEnabled && !await this.isValidServerToken(token);
346
+ return options;
347
+ };
348
+ _shouldPermissionsBeApplied = new WeakSet();
349
+ shouldPermissionsBeApplied_fn = async function(options) {
350
+ if (!__privateGet(this, _permissionEnabled)) {
351
+ return false;
307
352
  }
308
- }
353
+ let credentials;
354
+ if (options && "credentials" in options) {
355
+ credentials = options.credentials;
356
+ } else {
357
+ if (!(options == null ? void 0 : options.token)) {
358
+ return true;
359
+ }
360
+ try {
361
+ credentials = await __privateGet(this, _auth).authenticate(options.token);
362
+ } catch {
363
+ return true;
364
+ }
365
+ }
366
+ if (__privateGet(this, _auth).isPrincipal(credentials, "service")) {
367
+ return false;
368
+ }
369
+ return true;
370
+ };
371
+ let ServerPermissionClient = _ServerPermissionClient;
309
372
 
310
373
  exports.ServerPermissionClient = ServerPermissionClient;
311
374
  exports.createConditionAuthorizer = createConditionAuthorizer;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/integration/createConditionFactory.ts","../src/integration/createConditionExports.ts","../src/integration/util.ts","../src/integration/createConditionTransformer.ts","../src/integration/createPermissionIntegrationRouter.ts","../src/integration/createPermissionRule.ts","../src/ServerPermissionClient.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 {\n PermissionCondition,\n PermissionRuleParams,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\n/**\n * Creates a condition factory function for a given authorization rule and parameter types.\n *\n * @remarks\n *\n * For example, an isEntityOwner rule for catalog entities might take an array of entityRef strings.\n * The rule itself defines _how_ to check a given resource, whereas a condition also includes _what_\n * to verify.\n *\n * Plugin authors should generally use the {@link createConditionExports} in order to efficiently\n * create multiple condition factories. This helper should generally only be used to construct\n * condition factories for third-party rules that aren't part of the backend plugin with which\n * they're intended to integrate.\n *\n * @public\n */\nexport const createConditionFactory = <\n TResourceType extends string,\n TParams extends PermissionRuleParams = PermissionRuleParams,\n>(\n rule: PermissionRule<unknown, unknown, TResourceType, TParams>,\n) => {\n return (params: TParams): PermissionCondition<TResourceType, TParams> => {\n return {\n rule: rule.name,\n resourceType: rule.resourceType,\n params,\n };\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthorizeResult,\n ConditionalPolicyDecision,\n PermissionCondition,\n PermissionCriteria,\n ResourcePermission,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport { createConditionFactory } from './createConditionFactory';\n\n/**\n * A utility type for mapping a single {@link PermissionRule} to its\n * corresponding {@link @backstage/plugin-permission-common#PermissionCondition}.\n *\n * @public\n */\nexport type Condition<TRule> = TRule extends PermissionRule<\n any,\n any,\n infer TResourceType,\n infer TParams\n>\n ? undefined extends TParams\n ? () => PermissionCondition<TResourceType, TParams>\n : (params: TParams) => PermissionCondition<TResourceType, TParams>\n : never;\n\n/**\n * A utility type for mapping {@link PermissionRule}s to their corresponding\n * {@link @backstage/plugin-permission-common#PermissionCondition}s.\n *\n * @public\n */\nexport type Conditions<\n TRules extends Record<string, PermissionRule<any, any, any>>,\n> = {\n [Name in keyof TRules]: Condition<TRules[Name]>;\n};\n\n/**\n * Creates the recommended condition-related exports for a given plugin based on\n * the built-in {@link PermissionRule}s it supports.\n *\n * @remarks\n *\n * The function returns a `conditions` object containing a\n * {@link @backstage/plugin-permission-common#PermissionCondition} factory for\n * each of the supplied {@link PermissionRule}s, along with a\n * `createConditionalDecision` function which builds the wrapper object needed\n * to enclose conditions when authoring {@link PermissionPolicy}\n * implementations.\n *\n * Plugin authors should generally call this method with all the built-in\n * {@link PermissionRule}s the plugin supports, and export the resulting\n * `conditions` object and `createConditionalDecision` function so that they can\n * be used by {@link PermissionPolicy} authors.\n *\n * @public\n */\nexport const createConditionExports = <\n TResourceType extends string,\n TResource,\n TRules extends Record<string, PermissionRule<TResource, any, TResourceType>>,\n>(options: {\n pluginId: string;\n resourceType: TResourceType;\n rules: TRules;\n}): {\n conditions: Conditions<TRules>;\n createConditionalDecision: (\n permission: ResourcePermission<TResourceType>,\n conditions: PermissionCriteria<PermissionCondition<TResourceType>>,\n ) => ConditionalPolicyDecision;\n} => {\n const { pluginId, resourceType, rules } = options;\n\n return {\n conditions: Object.entries(rules).reduce(\n (acc, [key, rule]) => ({\n ...acc,\n [key]: createConditionFactory(rule),\n }),\n {} as Conditions<TRules>,\n ),\n createConditionalDecision: (\n _permission: ResourcePermission<TResourceType>,\n conditions: PermissionCriteria<PermissionCondition>,\n ) => ({\n result: AuthorizeResult.CONDITIONAL,\n pluginId,\n resourceType,\n conditions,\n }),\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AllOfCriteria,\n AnyOfCriteria,\n NotCriteria,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\n/**\n * Prevent use of type parameter from contributing to type inference.\n *\n * https://github.com/Microsoft/TypeScript/issues/14829#issuecomment-980401795\n * @ignore\n */\nexport type NoInfer<T> = T extends infer S ? S : never;\n\n/**\n * Utility function used to parse a PermissionCriteria\n * @param criteria - a PermissionCriteria\n * @public\n *\n * @returns `true` if the permission criteria is of type allOf,\n * narrowing down `criteria` to the specific type.\n */\nexport const isAndCriteria = <T>(\n criteria: PermissionCriteria<T>,\n): criteria is AllOfCriteria<T> =>\n Object.prototype.hasOwnProperty.call(criteria, 'allOf');\n\n/**\n * Utility function used to parse a PermissionCriteria of type\n * @param criteria - a PermissionCriteria\n * @public\n *\n * @returns `true` if the permission criteria is of type anyOf,\n * narrowing down `criteria` to the specific type.\n */\nexport const isOrCriteria = <T>(\n criteria: PermissionCriteria<T>,\n): criteria is AnyOfCriteria<T> =>\n Object.prototype.hasOwnProperty.call(criteria, 'anyOf');\n\n/**\n * Utility function used to parse a PermissionCriteria\n * @param criteria - a PermissionCriteria\n * @public\n *\n * @returns `true` if the permission criteria is of type not,\n * narrowing down `criteria` to the specific type.\n */\nexport const isNotCriteria = <T>(\n criteria: PermissionCriteria<T>,\n): criteria is NotCriteria<T> =>\n Object.prototype.hasOwnProperty.call(criteria, 'not');\n\nexport const createGetRule = <TResource, TQuery>(\n rules: PermissionRule<TResource, TQuery, string>[],\n) => {\n const rulesMap = new Map(Object.values(rules).map(rule => [rule.name, rule]));\n\n return (name: string): PermissionRule<TResource, TQuery, string> => {\n const rule = rulesMap.get(name);\n\n if (!rule) {\n throw new Error(`Unexpected permission rule: ${name}`);\n }\n\n return rule;\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { InputError } from '@backstage/errors';\nimport {\n AllOfCriteria,\n AnyOfCriteria,\n PermissionCondition,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport {\n createGetRule,\n isAndCriteria,\n isNotCriteria,\n isOrCriteria,\n} from './util';\n\nconst mapConditions = <TQuery>(\n criteria: PermissionCriteria<PermissionCondition>,\n getRule: (name: string) => PermissionRule<unknown, TQuery, string>,\n): PermissionCriteria<TQuery> => {\n if (isAndCriteria(criteria)) {\n return {\n allOf: criteria.allOf.map(child => mapConditions(child, getRule)),\n } as AllOfCriteria<TQuery>;\n } else if (isOrCriteria(criteria)) {\n return {\n anyOf: criteria.anyOf.map(child => mapConditions(child, getRule)),\n } as AnyOfCriteria<TQuery>;\n } else if (isNotCriteria(criteria)) {\n return {\n not: mapConditions(criteria.not, getRule),\n };\n }\n\n const rule = getRule(criteria.rule);\n const result = rule.paramsSchema?.safeParse(criteria.params);\n\n if (result && !result.success) {\n throw new InputError(`Parameters to rule are invalid`, result.error);\n }\n\n return rule.toQuery(criteria.params ?? {});\n};\n\n/**\n * A function which accepts {@link @backstage/plugin-permission-common#PermissionCondition}s\n * logically grouped in a {@link @backstage/plugin-permission-common#PermissionCriteria}\n * object, and transforms the {@link @backstage/plugin-permission-common#PermissionCondition}s\n * into plugin specific query fragments while retaining the enclosing criteria shape.\n *\n * @public\n */\nexport type ConditionTransformer<TQuery> = (\n conditions: PermissionCriteria<PermissionCondition>,\n) => PermissionCriteria<TQuery>;\n\n/**\n * A higher-order helper function which accepts an array of\n * {@link PermissionRule}s, and returns a {@link ConditionTransformer}\n * which transforms input conditions into equivalent plugin-specific\n * query fragments using the supplied rules.\n *\n * @public\n */\nexport const createConditionTransformer = <\n TQuery,\n TRules extends PermissionRule<any, TQuery, string>[],\n>(\n permissionRules: [...TRules],\n): ConditionTransformer<TQuery> => {\n const getRule = createGetRule(permissionRules);\n\n return conditions => mapConditions(conditions, getRule);\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express, { Response } from 'express';\nimport Router from 'express-promise-router';\nimport { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\nimport { InputError } from '@backstage/errors';\nimport { errorHandler } from '@backstage/backend-common';\nimport {\n AuthorizeResult,\n DefinitivePolicyDecision,\n IdentifiedPermissionMessage,\n Permission,\n PermissionCondition,\n PermissionCriteria,\n PolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport {\n NoInfer,\n createGetRule,\n isAndCriteria,\n isNotCriteria,\n isOrCriteria,\n} from './util';\nimport { NotImplementedError } from '@backstage/errors';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z.union([\n z.object({ anyOf: z.array(permissionCriteriaSchema).nonempty() }),\n z.object({ allOf: z.array(permissionCriteriaSchema).nonempty() }),\n z.object({ not: permissionCriteriaSchema }),\n z.object({\n rule: z.string(),\n resourceType: z.string(),\n params: z.record(z.any()).optional(),\n }),\n ]),\n);\n\nconst applyConditionsRequestSchema = z.object({\n items: z.array(\n z.object({\n id: z.string(),\n resourceRef: z.string(),\n resourceType: z.string(),\n conditions: permissionCriteriaSchema,\n }),\n ),\n});\n\n/**\n * A request to load the referenced resource and apply conditions in order to\n * finalize a conditional authorization response.\n *\n * @public\n */\nexport type ApplyConditionsRequestEntry = IdentifiedPermissionMessage<{\n resourceRef: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n}>;\n\n/**\n * A batch of {@link ApplyConditionsRequestEntry} objects.\n *\n * @public\n */\nexport type ApplyConditionsRequest = {\n items: ApplyConditionsRequestEntry[];\n};\n\n/**\n * The result of applying the conditions, expressed as a definitive authorize\n * result of ALLOW or DENY.\n *\n * @public\n */\nexport type ApplyConditionsResponseEntry =\n IdentifiedPermissionMessage<DefinitivePolicyDecision>;\n\n/**\n * A batch of {@link ApplyConditionsResponseEntry} objects.\n *\n * @public\n */\nexport type ApplyConditionsResponse = {\n items: ApplyConditionsResponseEntry[];\n};\n\n/**\n * Serialized permission rules, with the paramsSchema\n * converted from a ZodSchema to a JsonSchema.\n *\n * @public\n */\nexport type MetadataResponseSerializedRule = {\n name: string;\n description: string;\n resourceType: string;\n paramsSchema?: ReturnType<typeof zodToJsonSchema>;\n};\n\n/**\n * Response type for the .metadata endpoint.\n *\n * @public\n */\nexport type MetadataResponse = {\n permissions?: Permission[];\n rules: MetadataResponseSerializedRule[];\n};\n\nconst applyConditions = <TResourceType extends string, TResource>(\n criteria: PermissionCriteria<PermissionCondition<TResourceType>>,\n resource: TResource | undefined,\n getRule: (name: string) => PermissionRule<TResource, unknown, TResourceType>,\n): boolean => {\n // If resource was not found, deny. This avoids leaking information from the\n // apply-conditions API which would allow a user to differentiate between\n // non-existent resources and resources to which they do not have access.\n if (resource === undefined) {\n return false;\n }\n\n if (isAndCriteria(criteria)) {\n return criteria.allOf.every(child =>\n applyConditions(child, resource, getRule),\n );\n } else if (isOrCriteria(criteria)) {\n return criteria.anyOf.some(child =>\n applyConditions(child, resource, getRule),\n );\n } else if (isNotCriteria(criteria)) {\n return !applyConditions(criteria.not, resource, getRule);\n }\n\n const rule = getRule(criteria.rule);\n const result = rule.paramsSchema?.safeParse(criteria.params);\n\n if (result && !result.success) {\n throw new InputError(`Parameters to rule are invalid`, result.error);\n }\n\n return rule.apply(resource, criteria.params ?? {});\n};\n\n/**\n\n * Takes some permission conditions and returns a definitive authorization result\n * on the resource to which they apply.\n *\n * @public\n */\nexport const createConditionAuthorizer = <TResource, TQuery>(\n rules: PermissionRule<TResource, TQuery, string>[],\n) => {\n const getRule = createGetRule(rules);\n\n return (\n decision: PolicyDecision,\n resource: TResource | undefined,\n ): boolean => {\n if (decision.result === AuthorizeResult.CONDITIONAL) {\n return applyConditions(decision.conditions, resource, getRule);\n }\n\n return decision.result === AuthorizeResult.ALLOW;\n };\n};\n\n/**\n * Options for creating a permission integration router specific\n * for a particular resource type.\n *\n * @public\n */\nexport type CreatePermissionIntegrationRouterResourceOptions<\n TResourceType extends string,\n TResource,\n> = {\n resourceType: TResourceType;\n permissions?: Array<Permission>;\n // Do not infer value of TResourceType from supplied rules.\n // instead only consider the resourceType parameter, and\n // consider any rules whose resource type does not match\n // to be an error.\n rules: PermissionRule<TResource, any, NoInfer<TResourceType>>[];\n getResources?: (\n resourceRefs: string[],\n ) => Promise<Array<TResource | undefined>>;\n};\n\n/**\n * Options for creating a permission integration router exposing\n * permissions and rules from multiple resource types.\n *\n * @public\n */\nexport type PermissionIntegrationRouterOptions<\n TResourceType1 extends string = string,\n TResource1 = any,\n TResourceType2 extends string = string,\n TResource2 = any,\n TResourceType3 extends string = string,\n TResource3 = any,\n> = {\n resources: Readonly<\n | [\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n ]\n | [\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType2,\n TResource2\n >,\n ]\n | [\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType2,\n TResource2\n >,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType3,\n TResource3\n >,\n ]\n >;\n};\n\n/**\n * Create an express Router which provides an authorization route to allow\n * integration between the permission backend and other Backstage backend\n * plugins. Plugin owners that wish to support conditional authorization for\n * their resources should add the router created by this function to their\n * express app inside their `createRouter` implementation.\n *\n * In case the `permissions` option is provided, the router also\n * provides a route that exposes permissions and routes of a plugin.\n *\n * In case resources is provided, the routes can handle permissions\n * for multiple resource types.\n *\n * @remarks\n *\n * To make this concrete, we can use the Backstage software catalog as an\n * example. The catalog has conditional rules around access to specific\n * _entities_ in the catalog. The _type_ of resource is captured here as\n * `resourceType`, a string identifier (`catalog-entity` in this example) that\n * can be provided with permission definitions. This is merely a _type_ to\n * verify that conditions in an authorization policy are constructed correctly,\n * not a reference to a specific resource.\n *\n * The `rules` parameter is an array of {@link PermissionRule}s that introduce\n * conditional filtering logic for resources; for the catalog, these are things\n * like `isEntityOwner` or `hasAnnotation`. Rules describe how to filter a list\n * of resources, and the `conditions` returned allow these rules to be applied\n * with specific parameters (such as 'group:default/team-a', or\n * 'backstage.io/edit-url').\n *\n * The `getResources` argument should load resources based on a reference\n * identifier. For the catalog, this is an\n * {@link @backstage/catalog-model#EntityRef}. For other plugins, this can be\n * any serialized format. This is used to construct the\n * `createPermissionIntegrationRouter`, a function to add an authorization route\n * to your backend plugin. This function will be called by the\n * `permission-backend` when authorization conditions relating to this plugin\n * need to be evaluated.\n *\n * @public\n */\nexport function createPermissionIntegrationRouter<\n TResourceType1 extends string,\n TResource1,\n TResourceType2 extends string,\n TResource2,\n TResourceType3 extends string,\n TResource3,\n>(\n options:\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >\n | PermissionIntegrationRouterOptions<\n TResourceType1,\n TResource1,\n TResourceType2,\n TResource2,\n TResourceType3,\n TResource3\n >,\n): express.Router {\n const optionsWithResources = options as PermissionIntegrationRouterOptions;\n const allOptions = [\n optionsWithResources.resources ? optionsWithResources.resources : options,\n ].flat();\n const allRules = allOptions.flatMap(\n option =>\n (\n option as CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >\n ).rules || [],\n );\n const allPermissions = [\n ...((options as { permissions: Permission[] }).permissions || []),\n ...(optionsWithResources.resources?.flatMap(o => o.permissions || []) ||\n []),\n ];\n\n const allResourceTypes = allOptions.reduce((acc, option) => {\n if (\n isCreatePermissionIntegrationRouterResourceOptions(\n option as\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n )\n ) {\n acc.push(\n (\n option as CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >\n ).resourceType,\n );\n }\n return acc;\n }, [] as string[]);\n\n const router = Router();\n router.use(express.json());\n\n router.get('/.well-known/backstage/permissions/metadata', (_, res) => {\n const serializedRules: MetadataResponseSerializedRule[] = allRules.map(\n rule => ({\n name: rule.name,\n description: rule.description,\n resourceType: rule.resourceType,\n paramsSchema: zodToJsonSchema(rule.paramsSchema ?? z.object({})),\n }),\n );\n\n const responseJson: MetadataResponse = {\n permissions: allPermissions,\n rules: serializedRules,\n };\n\n return res.json(responseJson);\n });\n\n router.post(\n '/.well-known/backstage/permissions/apply-conditions',\n async (req, res: Response<ApplyConditionsResponse | string>) => {\n const ruleMapByResourceType: Record<\n string,\n ReturnType<typeof createGetRule>\n > = {};\n const getResourcesByResourceType: Record<\n string,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >['getResources']\n > = {};\n\n for (let option of allOptions) {\n option = option as\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >;\n if (isCreatePermissionIntegrationRouterResourceOptions(option)) {\n ruleMapByResourceType[option.resourceType] = createGetRule(\n option.rules,\n );\n\n getResourcesByResourceType[option.resourceType] = option.getResources;\n }\n }\n\n const assertValidResourceTypes = (\n requests: ApplyConditionsRequestEntry[],\n ) => {\n const invalidResourceTypes = requests\n .filter(request => !allResourceTypes.includes(request.resourceType))\n .map(request => request.resourceType);\n\n if (invalidResourceTypes.length) {\n throw new InputError(\n `Unexpected resource types: ${invalidResourceTypes.join(', ')}.`,\n );\n }\n };\n\n const parseResult = applyConditionsRequestSchema.safeParse(req.body);\n\n if (!parseResult.success) {\n throw new InputError(parseResult.error.toString());\n }\n\n const body = parseResult.data;\n\n assertValidResourceTypes(body.items);\n\n const resourceRefsByResourceType = body.items.reduce<\n Record<string, Set<string>>\n >((acc, item) => {\n if (!acc[item.resourceType]) {\n acc[item.resourceType] = new Set();\n }\n acc[item.resourceType].add(item.resourceRef);\n return acc;\n }, {});\n\n const resourcesByResourceType: Record<string, Record<string, any>> = {};\n for (const resourceType of Object.keys(resourceRefsByResourceType)) {\n const getResources = getResourcesByResourceType[resourceType];\n if (!getResources) {\n throw new NotImplementedError(\n `This plugin does not expose any permission rule or can't evaluate the conditions request for ${resourceType}`,\n );\n }\n const resourceRefs = Array.from(\n resourceRefsByResourceType[resourceType],\n );\n const resources = await getResources(resourceRefs);\n resourceRefs.forEach((resourceRef, index) => {\n if (!resourcesByResourceType[resourceType]) {\n resourcesByResourceType[resourceType] = {};\n }\n resourcesByResourceType[resourceType][resourceRef] = resources[index];\n });\n }\n\n return res.json({\n items: body.items.map(request => ({\n id: request.id,\n result: applyConditions(\n request.conditions,\n resourcesByResourceType[request.resourceType][request.resourceRef],\n ruleMapByResourceType[request.resourceType],\n )\n ? AuthorizeResult.ALLOW\n : AuthorizeResult.DENY,\n })),\n });\n },\n );\n\n router.use(errorHandler());\n\n return router;\n}\n\nfunction isCreatePermissionIntegrationRouterResourceOptions<\n TResourceType extends string,\n TResource,\n>(\n options:\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType,\n TResource\n >,\n): options is CreatePermissionIntegrationRouterResourceOptions<\n TResourceType,\n TResource\n> {\n return (\n (\n options as CreatePermissionIntegrationRouterResourceOptions<\n TResourceType,\n TResource\n >\n ).resourceType !== undefined\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 { PermissionRuleParams } from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\n/**\n * Helper function to ensure that {@link PermissionRule} definitions are typed correctly.\n *\n * @public\n */\nexport const createPermissionRule = <\n TResource,\n TQuery,\n TResourceType extends string,\n TParams extends PermissionRuleParams = undefined,\n>(\n rule: PermissionRule<TResource, TQuery, TResourceType, TParams>,\n) => rule;\n\n/**\n * Helper for making plugin-specific createPermissionRule functions, that have\n * the TResource and TQuery type parameters populated but infer the params from\n * the supplied rule. This helps ensure that rules created for this plugin use\n * consistent types for the resource and query.\n *\n * @public\n */\nexport const makeCreatePermissionRule =\n <TResource, TQuery, TResourceType extends string>() =>\n <TParams extends PermissionRuleParams = undefined>(\n rule: PermissionRule<TResource, TQuery, TResourceType, TParams>,\n ) =>\n createPermissionRule(rule);\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 TokenManager,\n PluginEndpointDiscovery,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport {\n AuthorizeResult,\n PermissionClient,\n PermissionEvaluator,\n AuthorizePermissionRequest,\n EvaluatorRequestOptions,\n AuthorizePermissionResponse,\n PolicyDecision,\n QueryPermissionRequest,\n} from '@backstage/plugin-permission-common';\n\n/**\n * A thin wrapper around\n * {@link @backstage/plugin-permission-common#PermissionClient} that allows all\n * service-to-service requests.\n * @public\n */\nexport class ServerPermissionClient implements PermissionEvaluator {\n private readonly permissionClient: PermissionClient;\n private readonly tokenManager: TokenManager;\n private readonly permissionEnabled: boolean;\n\n static fromConfig(\n config: Config,\n options: {\n discovery: PluginEndpointDiscovery;\n tokenManager: TokenManager;\n },\n ) {\n const { discovery, tokenManager } = options;\n const permissionClient = new PermissionClient({ discovery, config });\n const permissionEnabled =\n config.getOptionalBoolean('permission.enabled') ?? false;\n\n if (\n permissionEnabled &&\n (tokenManager as any).isInsecureServerTokenManager\n ) {\n throw new Error(\n 'Service-to-service authentication must be configured before enabling permissions. Read more here https://backstage.io/docs/auth/service-to-service-auth',\n );\n }\n\n return new ServerPermissionClient({\n permissionClient,\n tokenManager,\n permissionEnabled,\n });\n }\n\n private constructor(options: {\n permissionClient: PermissionClient;\n tokenManager: TokenManager;\n permissionEnabled: boolean;\n }) {\n this.permissionClient = options.permissionClient;\n this.tokenManager = options.tokenManager;\n this.permissionEnabled = options.permissionEnabled;\n }\n\n async authorizeConditional(\n queries: QueryPermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<PolicyDecision[]> {\n return (await this.isEnabled(options?.token))\n ? this.permissionClient.authorizeConditional(queries, options)\n : queries.map(_ => ({ result: AuthorizeResult.ALLOW }));\n }\n\n async authorize(\n requests: AuthorizePermissionRequest[],\n options?: EvaluatorRequestOptions,\n ): Promise<AuthorizePermissionResponse[]> {\n return (await this.isEnabled(options?.token))\n ? this.permissionClient.authorize(requests, options)\n : requests.map(_ => ({ result: AuthorizeResult.ALLOW }));\n }\n\n private async isValidServerToken(\n token: string | undefined,\n ): Promise<boolean> {\n if (!token) {\n return false;\n }\n return this.tokenManager\n .authenticate(token)\n .then(() => true)\n .catch(() => false);\n }\n\n private async isEnabled(token?: string) {\n // Check if permissions are enabled before validating the server token. That\n // way when permissions are disabled, the noop token manager can be used\n // without fouling up the logic inside the ServerPermissionClient, because\n // the code path won't be reached.\n return this.permissionEnabled && !(await this.isValidServerToken(token));\n }\n}\n"],"names":["AuthorizeResult","InputError","z","Router","express","_a","zodToJsonSchema","NotImplementedError","errorHandler","PermissionClient"],"mappings":";;;;;;;;;;;;;;;;;;AAsCa,MAAA,sBAAA,GAAyB,CAIpC,IACG,KAAA;AACH,EAAA,OAAO,CAAC,MAAiE,KAAA;AACvE,IAAO,OAAA;AAAA,MACL,MAAM,IAAK,CAAA,IAAA;AAAA,MACX,cAAc,IAAK,CAAA,YAAA;AAAA,MACnB,MAAA;AAAA,KACF,CAAA;AAAA,GACF,CAAA;AACF;;ACwBa,MAAA,sBAAA,GAAyB,CAIpC,OAUG,KAAA;AACH,EAAA,MAAM,EAAE,QAAA,EAAU,YAAc,EAAA,KAAA,EAAU,GAAA,OAAA,CAAA;AAE1C,EAAO,OAAA;AAAA,IACL,UAAY,EAAA,MAAA,CAAO,OAAQ,CAAA,KAAK,CAAE,CAAA,MAAA;AAAA,MAChC,CAAC,GAAA,EAAK,CAAC,GAAA,EAAK,IAAI,CAAO,MAAA;AAAA,QACrB,GAAG,GAAA;AAAA,QACH,CAAC,GAAG,GAAG,sBAAA,CAAuB,IAAI,CAAA;AAAA,OACpC,CAAA;AAAA,MACA,EAAC;AAAA,KACH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,CAAA,OAAA,EACA,OAC2B,EAAA;AAC3B,IAAA,OAAQ,MAAM,IAAK,CAAA,SAAA,CAAU,mCAAS,KAAK,CAAA,GACvC,KAAK,gBAAiB,CAAA,oBAAA,CAAqB,SAAS,OAAO,CAAA,GAC3D,QAAQ,GAAI,CAAA,CAAA,CAAA,MAAM,EAAE,MAAQ,EAAAT,sCAAA,CAAgB,OAAQ,CAAA,CAAA,CAAA;AAAA,GAC1D;AAAA,EAEA,MAAM,SACJ,CAAA,QAAA,EACA,OACwC,EAAA;AACxC,IAAA,OAAQ,MAAM,IAAK,CAAA,SAAA,CAAU,mCAAS,KAAK,CAAA,GACvC,KAAK,gBAAiB,CAAA,SAAA,CAAU,UAAU,OAAO,CAAA,GACjD,SAAS,GAAI,CAAA,CAAA,CAAA,MAAM,EAAE,MAAQ,EAAAA,sCAAA,CAAgB,OAAQ,CAAA,CAAA,CAAA;AAAA,GAC3D;AAAA,EAEA,MAAc,mBACZ,KACkB,EAAA;AAClB,IAAA,IAAI,CAAC,KAAO,EAAA;AACV,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AACA,IAAO,OAAA,IAAA,CAAK,YACT,CAAA,YAAA,CAAa,KAAK,CAAA,CAClB,IAAK,CAAA,MAAM,IAAI,CAAA,CACf,KAAM,CAAA,MAAM,KAAK,CAAA,CAAA;AAAA,GACtB;AAAA,EAEA,MAAc,UAAU,KAAgB,EAAA;AAKtC,IAAA,OAAO,KAAK,iBAAqB,IAAA,CAAE,MAAM,IAAA,CAAK,mBAAmB,KAAK,CAAA,CAAA;AAAA,GACxE;AACF;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/integration/createConditionFactory.ts","../src/integration/createConditionExports.ts","../src/integration/util.ts","../src/integration/createConditionTransformer.ts","../src/integration/createPermissionIntegrationRouter.ts","../src/integration/createPermissionRule.ts","../src/ServerPermissionClient.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 {\n PermissionCondition,\n PermissionRuleParams,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\n/**\n * Creates a condition factory function for a given authorization rule and parameter types.\n *\n * @remarks\n *\n * For example, an isEntityOwner rule for catalog entities might take an array of entityRef strings.\n * The rule itself defines _how_ to check a given resource, whereas a condition also includes _what_\n * to verify.\n *\n * Plugin authors should generally use the {@link createConditionExports} in order to efficiently\n * create multiple condition factories. This helper should generally only be used to construct\n * condition factories for third-party rules that aren't part of the backend plugin with which\n * they're intended to integrate.\n *\n * @public\n */\nexport const createConditionFactory = <\n TResourceType extends string,\n TParams extends PermissionRuleParams = PermissionRuleParams,\n>(\n rule: PermissionRule<unknown, unknown, TResourceType, TParams>,\n) => {\n return (params: TParams): PermissionCondition<TResourceType, TParams> => {\n return {\n rule: rule.name,\n resourceType: rule.resourceType,\n params,\n };\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthorizeResult,\n ConditionalPolicyDecision,\n PermissionCondition,\n PermissionCriteria,\n ResourcePermission,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport { createConditionFactory } from './createConditionFactory';\n\n/**\n * A utility type for mapping a single {@link PermissionRule} to its\n * corresponding {@link @backstage/plugin-permission-common#PermissionCondition}.\n *\n * @public\n */\nexport type Condition<TRule> = TRule extends PermissionRule<\n any,\n any,\n infer TResourceType,\n infer TParams\n>\n ? undefined extends TParams\n ? () => PermissionCondition<TResourceType, TParams>\n : (params: TParams) => PermissionCondition<TResourceType, TParams>\n : never;\n\n/**\n * A utility type for mapping {@link PermissionRule}s to their corresponding\n * {@link @backstage/plugin-permission-common#PermissionCondition}s.\n *\n * @public\n */\nexport type Conditions<\n TRules extends Record<string, PermissionRule<any, any, any>>,\n> = {\n [Name in keyof TRules]: Condition<TRules[Name]>;\n};\n\n/**\n * Creates the recommended condition-related exports for a given plugin based on\n * the built-in {@link PermissionRule}s it supports.\n *\n * @remarks\n *\n * The function returns a `conditions` object containing a\n * {@link @backstage/plugin-permission-common#PermissionCondition} factory for\n * each of the supplied {@link PermissionRule}s, along with a\n * `createConditionalDecision` function which builds the wrapper object needed\n * to enclose conditions when authoring {@link PermissionPolicy}\n * implementations.\n *\n * Plugin authors should generally call this method with all the built-in\n * {@link PermissionRule}s the plugin supports, and export the resulting\n * `conditions` object and `createConditionalDecision` function so that they can\n * be used by {@link PermissionPolicy} authors.\n *\n * @public\n */\nexport const createConditionExports = <\n TResourceType extends string,\n TResource,\n TRules extends Record<string, PermissionRule<TResource, any, TResourceType>>,\n>(options: {\n pluginId: string;\n resourceType: TResourceType;\n rules: TRules;\n}): {\n conditions: Conditions<TRules>;\n createConditionalDecision: (\n permission: ResourcePermission<TResourceType>,\n conditions: PermissionCriteria<PermissionCondition<TResourceType>>,\n ) => ConditionalPolicyDecision;\n} => {\n const { pluginId, resourceType, rules } = options;\n\n return {\n conditions: Object.entries(rules).reduce(\n (acc, [key, rule]) => ({\n ...acc,\n [key]: createConditionFactory(rule),\n }),\n {} as Conditions<TRules>,\n ),\n createConditionalDecision: (\n _permission: ResourcePermission<TResourceType>,\n conditions: PermissionCriteria<PermissionCondition>,\n ) => ({\n result: AuthorizeResult.CONDITIONAL,\n pluginId,\n resourceType,\n conditions,\n }),\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AllOfCriteria,\n AnyOfCriteria,\n NotCriteria,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\n/**\n * Prevent use of type parameter from contributing to type inference.\n *\n * https://github.com/Microsoft/TypeScript/issues/14829#issuecomment-980401795\n * @ignore\n */\nexport type NoInfer<T> = T extends infer S ? S : never;\n\n/**\n * Utility function used to parse a PermissionCriteria\n * @param criteria - a PermissionCriteria\n * @public\n *\n * @returns `true` if the permission criteria is of type allOf,\n * narrowing down `criteria` to the specific type.\n */\nexport const isAndCriteria = <T>(\n criteria: PermissionCriteria<T>,\n): criteria is AllOfCriteria<T> =>\n Object.prototype.hasOwnProperty.call(criteria, 'allOf');\n\n/**\n * Utility function used to parse a PermissionCriteria of type\n * @param criteria - a PermissionCriteria\n * @public\n *\n * @returns `true` if the permission criteria is of type anyOf,\n * narrowing down `criteria` to the specific type.\n */\nexport const isOrCriteria = <T>(\n criteria: PermissionCriteria<T>,\n): criteria is AnyOfCriteria<T> =>\n Object.prototype.hasOwnProperty.call(criteria, 'anyOf');\n\n/**\n * Utility function used to parse a PermissionCriteria\n * @param criteria - a PermissionCriteria\n * @public\n *\n * @returns `true` if the permission criteria is of type not,\n * narrowing down `criteria` to the specific type.\n */\nexport const isNotCriteria = <T>(\n criteria: PermissionCriteria<T>,\n): criteria is NotCriteria<T> =>\n Object.prototype.hasOwnProperty.call(criteria, 'not');\n\nexport const createGetRule = <TResource, TQuery>(\n rules: PermissionRule<TResource, TQuery, string>[],\n) => {\n const rulesMap = new Map(Object.values(rules).map(rule => [rule.name, rule]));\n\n return (name: string): PermissionRule<TResource, TQuery, string> => {\n const rule = rulesMap.get(name);\n\n if (!rule) {\n throw new Error(`Unexpected permission rule: ${name}`);\n }\n\n return rule;\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { InputError } from '@backstage/errors';\nimport {\n AllOfCriteria,\n AnyOfCriteria,\n PermissionCondition,\n PermissionCriteria,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport {\n createGetRule,\n isAndCriteria,\n isNotCriteria,\n isOrCriteria,\n} from './util';\n\nconst mapConditions = <TQuery>(\n criteria: PermissionCriteria<PermissionCondition>,\n getRule: (name: string) => PermissionRule<unknown, TQuery, string>,\n): PermissionCriteria<TQuery> => {\n if (isAndCriteria(criteria)) {\n return {\n allOf: criteria.allOf.map(child => mapConditions(child, getRule)),\n } as AllOfCriteria<TQuery>;\n } else if (isOrCriteria(criteria)) {\n return {\n anyOf: criteria.anyOf.map(child => mapConditions(child, getRule)),\n } as AnyOfCriteria<TQuery>;\n } else if (isNotCriteria(criteria)) {\n return {\n not: mapConditions(criteria.not, getRule),\n };\n }\n\n const rule = getRule(criteria.rule);\n const result = rule.paramsSchema?.safeParse(criteria.params);\n\n if (result && !result.success) {\n throw new InputError(`Parameters to rule are invalid`, result.error);\n }\n\n return rule.toQuery(criteria.params ?? {});\n};\n\n/**\n * A function which accepts {@link @backstage/plugin-permission-common#PermissionCondition}s\n * logically grouped in a {@link @backstage/plugin-permission-common#PermissionCriteria}\n * object, and transforms the {@link @backstage/plugin-permission-common#PermissionCondition}s\n * into plugin specific query fragments while retaining the enclosing criteria shape.\n *\n * @public\n */\nexport type ConditionTransformer<TQuery> = (\n conditions: PermissionCriteria<PermissionCondition>,\n) => PermissionCriteria<TQuery>;\n\n/**\n * A higher-order helper function which accepts an array of\n * {@link PermissionRule}s, and returns a {@link ConditionTransformer}\n * which transforms input conditions into equivalent plugin-specific\n * query fragments using the supplied rules.\n *\n * @public\n */\nexport const createConditionTransformer = <\n TQuery,\n TRules extends PermissionRule<any, TQuery, string>[],\n>(\n permissionRules: [...TRules],\n): ConditionTransformer<TQuery> => {\n const getRule = createGetRule(permissionRules);\n\n return conditions => mapConditions(conditions, getRule);\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express, { Response } from 'express';\nimport Router from 'express-promise-router';\nimport { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\nimport { InputError } from '@backstage/errors';\nimport { errorHandler } from '@backstage/backend-common';\nimport {\n AuthorizeResult,\n DefinitivePolicyDecision,\n IdentifiedPermissionMessage,\n Permission,\n PermissionCondition,\n PermissionCriteria,\n PolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\nimport {\n NoInfer,\n createGetRule,\n isAndCriteria,\n isNotCriteria,\n isOrCriteria,\n} from './util';\nimport { NotImplementedError } from '@backstage/errors';\n\nconst permissionCriteriaSchema: z.ZodSchema<\n PermissionCriteria<PermissionCondition>\n> = z.lazy(() =>\n z.union([\n z.object({ anyOf: z.array(permissionCriteriaSchema).nonempty() }),\n z.object({ allOf: z.array(permissionCriteriaSchema).nonempty() }),\n z.object({ not: permissionCriteriaSchema }),\n z.object({\n rule: z.string(),\n resourceType: z.string(),\n params: z.record(z.any()).optional(),\n }),\n ]),\n);\n\nconst applyConditionsRequestSchema = z.object({\n items: z.array(\n z.object({\n id: z.string(),\n resourceRef: z.string(),\n resourceType: z.string(),\n conditions: permissionCriteriaSchema,\n }),\n ),\n});\n\n/**\n * A request to load the referenced resource and apply conditions in order to\n * finalize a conditional authorization response.\n *\n * @public\n */\nexport type ApplyConditionsRequestEntry = IdentifiedPermissionMessage<{\n resourceRef: string;\n resourceType: string;\n conditions: PermissionCriteria<PermissionCondition>;\n}>;\n\n/**\n * A batch of {@link ApplyConditionsRequestEntry} objects.\n *\n * @public\n */\nexport type ApplyConditionsRequest = {\n items: ApplyConditionsRequestEntry[];\n};\n\n/**\n * The result of applying the conditions, expressed as a definitive authorize\n * result of ALLOW or DENY.\n *\n * @public\n */\nexport type ApplyConditionsResponseEntry =\n IdentifiedPermissionMessage<DefinitivePolicyDecision>;\n\n/**\n * A batch of {@link ApplyConditionsResponseEntry} objects.\n *\n * @public\n */\nexport type ApplyConditionsResponse = {\n items: ApplyConditionsResponseEntry[];\n};\n\n/**\n * Serialized permission rules, with the paramsSchema\n * converted from a ZodSchema to a JsonSchema.\n *\n * @public\n */\nexport type MetadataResponseSerializedRule = {\n name: string;\n description: string;\n resourceType: string;\n paramsSchema?: ReturnType<typeof zodToJsonSchema>;\n};\n\n/**\n * Response type for the .metadata endpoint.\n *\n * @public\n */\nexport type MetadataResponse = {\n permissions?: Permission[];\n rules: MetadataResponseSerializedRule[];\n};\n\nconst applyConditions = <TResourceType extends string, TResource>(\n criteria: PermissionCriteria<PermissionCondition<TResourceType>>,\n resource: TResource | undefined,\n getRule: (name: string) => PermissionRule<TResource, unknown, TResourceType>,\n): boolean => {\n // If resource was not found, deny. This avoids leaking information from the\n // apply-conditions API which would allow a user to differentiate between\n // non-existent resources and resources to which they do not have access.\n if (resource === undefined) {\n return false;\n }\n\n if (isAndCriteria(criteria)) {\n return criteria.allOf.every(child =>\n applyConditions(child, resource, getRule),\n );\n } else if (isOrCriteria(criteria)) {\n return criteria.anyOf.some(child =>\n applyConditions(child, resource, getRule),\n );\n } else if (isNotCriteria(criteria)) {\n return !applyConditions(criteria.not, resource, getRule);\n }\n\n const rule = getRule(criteria.rule);\n const result = rule.paramsSchema?.safeParse(criteria.params);\n\n if (result && !result.success) {\n throw new InputError(`Parameters to rule are invalid`, result.error);\n }\n\n return rule.apply(resource, criteria.params ?? {});\n};\n\n/**\n\n * Takes some permission conditions and returns a definitive authorization result\n * on the resource to which they apply.\n *\n * @public\n */\nexport const createConditionAuthorizer = <TResource, TQuery>(\n rules: PermissionRule<TResource, TQuery, string>[],\n) => {\n const getRule = createGetRule(rules);\n\n return (\n decision: PolicyDecision,\n resource: TResource | undefined,\n ): boolean => {\n if (decision.result === AuthorizeResult.CONDITIONAL) {\n return applyConditions(decision.conditions, resource, getRule);\n }\n\n return decision.result === AuthorizeResult.ALLOW;\n };\n};\n\n/**\n * Options for creating a permission integration router specific\n * for a particular resource type.\n *\n * @public\n */\nexport type CreatePermissionIntegrationRouterResourceOptions<\n TResourceType extends string,\n TResource,\n> = {\n resourceType: TResourceType;\n permissions?: Array<Permission>;\n // Do not infer value of TResourceType from supplied rules.\n // instead only consider the resourceType parameter, and\n // consider any rules whose resource type does not match\n // to be an error.\n rules: PermissionRule<TResource, any, NoInfer<TResourceType>>[];\n getResources?: (\n resourceRefs: string[],\n ) => Promise<Array<TResource | undefined>>;\n};\n\n/**\n * Options for creating a permission integration router exposing\n * permissions and rules from multiple resource types.\n *\n * @public\n */\nexport type PermissionIntegrationRouterOptions<\n TResourceType1 extends string = string,\n TResource1 = any,\n TResourceType2 extends string = string,\n TResource2 = any,\n TResourceType3 extends string = string,\n TResource3 = any,\n> = {\n resources: Readonly<\n | [\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n ]\n | [\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType2,\n TResource2\n >,\n ]\n | [\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType2,\n TResource2\n >,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType3,\n TResource3\n >,\n ]\n >;\n};\n\n/**\n * Create an express Router which provides an authorization route to allow\n * integration between the permission backend and other Backstage backend\n * plugins. Plugin owners that wish to support conditional authorization for\n * their resources should add the router created by this function to their\n * express app inside their `createRouter` implementation.\n *\n * In case the `permissions` option is provided, the router also\n * provides a route that exposes permissions and routes of a plugin.\n *\n * In case resources is provided, the routes can handle permissions\n * for multiple resource types.\n *\n * @remarks\n *\n * To make this concrete, we can use the Backstage software catalog as an\n * example. The catalog has conditional rules around access to specific\n * _entities_ in the catalog. The _type_ of resource is captured here as\n * `resourceType`, a string identifier (`catalog-entity` in this example) that\n * can be provided with permission definitions. This is merely a _type_ to\n * verify that conditions in an authorization policy are constructed correctly,\n * not a reference to a specific resource.\n *\n * The `rules` parameter is an array of {@link PermissionRule}s that introduce\n * conditional filtering logic for resources; for the catalog, these are things\n * like `isEntityOwner` or `hasAnnotation`. Rules describe how to filter a list\n * of resources, and the `conditions` returned allow these rules to be applied\n * with specific parameters (such as 'group:default/team-a', or\n * 'backstage.io/edit-url').\n *\n * The `getResources` argument should load resources based on a reference\n * identifier. For the catalog, this is an\n * {@link @backstage/catalog-model#EntityRef}. For other plugins, this can be\n * any serialized format. This is used to construct the\n * `createPermissionIntegrationRouter`, a function to add an authorization route\n * to your backend plugin. This function will be called by the\n * `permission-backend` when authorization conditions relating to this plugin\n * need to be evaluated.\n *\n * @public\n */\nexport function createPermissionIntegrationRouter<\n TResourceType1 extends string,\n TResource1,\n TResourceType2 extends string,\n TResource2,\n TResourceType3 extends string,\n TResource3,\n>(\n options:\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >\n | PermissionIntegrationRouterOptions<\n TResourceType1,\n TResource1,\n TResourceType2,\n TResource2,\n TResourceType3,\n TResource3\n >,\n): express.Router {\n const optionsWithResources = options as PermissionIntegrationRouterOptions;\n const allOptions = [\n optionsWithResources.resources ? optionsWithResources.resources : options,\n ].flat();\n const allRules = allOptions.flatMap(\n option =>\n (\n option as CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >\n ).rules || [],\n );\n const allPermissions = [\n ...((options as { permissions: Permission[] }).permissions || []),\n ...(optionsWithResources.resources?.flatMap(o => o.permissions || []) ||\n []),\n ];\n\n const allResourceTypes = allOptions.reduce((acc, option) => {\n if (\n isCreatePermissionIntegrationRouterResourceOptions(\n option as\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >,\n )\n ) {\n acc.push(\n (\n option as CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >\n ).resourceType,\n );\n }\n return acc;\n }, [] as string[]);\n\n const router = Router();\n router.use(express.json());\n\n router.get('/.well-known/backstage/permissions/metadata', (_, res) => {\n const serializedRules: MetadataResponseSerializedRule[] = allRules.map(\n rule => ({\n name: rule.name,\n description: rule.description,\n resourceType: rule.resourceType,\n paramsSchema: zodToJsonSchema(rule.paramsSchema ?? z.object({})),\n }),\n );\n\n const responseJson: MetadataResponse = {\n permissions: allPermissions,\n rules: serializedRules,\n };\n\n return res.json(responseJson);\n });\n\n router.post(\n '/.well-known/backstage/permissions/apply-conditions',\n async (req, res: Response<ApplyConditionsResponse | string>) => {\n const ruleMapByResourceType: Record<\n string,\n ReturnType<typeof createGetRule>\n > = {};\n const getResourcesByResourceType: Record<\n string,\n CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >['getResources']\n > = {};\n\n for (let option of allOptions) {\n option = option as\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType1,\n TResource1\n >;\n if (isCreatePermissionIntegrationRouterResourceOptions(option)) {\n ruleMapByResourceType[option.resourceType] = createGetRule(\n option.rules,\n );\n\n getResourcesByResourceType[option.resourceType] = option.getResources;\n }\n }\n\n const assertValidResourceTypes = (\n requests: ApplyConditionsRequestEntry[],\n ) => {\n const invalidResourceTypes = requests\n .filter(request => !allResourceTypes.includes(request.resourceType))\n .map(request => request.resourceType);\n\n if (invalidResourceTypes.length) {\n throw new InputError(\n `Unexpected resource types: ${invalidResourceTypes.join(', ')}.`,\n );\n }\n };\n\n const parseResult = applyConditionsRequestSchema.safeParse(req.body);\n\n if (!parseResult.success) {\n throw new InputError(parseResult.error.toString());\n }\n\n const body = parseResult.data;\n\n assertValidResourceTypes(body.items);\n\n const resourceRefsByResourceType = body.items.reduce<\n Record<string, Set<string>>\n >((acc, item) => {\n if (!acc[item.resourceType]) {\n acc[item.resourceType] = new Set();\n }\n acc[item.resourceType].add(item.resourceRef);\n return acc;\n }, {});\n\n const resourcesByResourceType: Record<string, Record<string, any>> = {};\n for (const resourceType of Object.keys(resourceRefsByResourceType)) {\n const getResources = getResourcesByResourceType[resourceType];\n if (!getResources) {\n throw new NotImplementedError(\n `This plugin does not expose any permission rule or can't evaluate the conditions request for ${resourceType}`,\n );\n }\n const resourceRefs = Array.from(\n resourceRefsByResourceType[resourceType],\n );\n const resources = await getResources(resourceRefs);\n resourceRefs.forEach((resourceRef, index) => {\n if (!resourcesByResourceType[resourceType]) {\n resourcesByResourceType[resourceType] = {};\n }\n resourcesByResourceType[resourceType][resourceRef] = resources[index];\n });\n }\n\n return res.json({\n items: body.items.map(request => ({\n id: request.id,\n result: applyConditions(\n request.conditions,\n resourcesByResourceType[request.resourceType][request.resourceRef],\n ruleMapByResourceType[request.resourceType],\n )\n ? AuthorizeResult.ALLOW\n : AuthorizeResult.DENY,\n })),\n });\n },\n );\n\n router.use(errorHandler());\n\n return router;\n}\n\nfunction isCreatePermissionIntegrationRouterResourceOptions<\n TResourceType extends string,\n TResource,\n>(\n options:\n | { permissions: Array<Permission> }\n | CreatePermissionIntegrationRouterResourceOptions<\n TResourceType,\n TResource\n >,\n): options is CreatePermissionIntegrationRouterResourceOptions<\n TResourceType,\n TResource\n> {\n return (\n (\n options as CreatePermissionIntegrationRouterResourceOptions<\n TResourceType,\n TResource\n >\n ).resourceType !== undefined\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 { PermissionRuleParams } from '@backstage/plugin-permission-common';\nimport { PermissionRule } from '../types';\n\n/**\n * Helper function to ensure that {@link PermissionRule} definitions are typed correctly.\n *\n * @public\n */\nexport const createPermissionRule = <\n TResource,\n TQuery,\n TResourceType extends string,\n TParams extends PermissionRuleParams = undefined,\n>(\n rule: PermissionRule<TResource, TQuery, TResourceType, TParams>,\n) => rule;\n\n/**\n * Helper for making plugin-specific createPermissionRule functions, that have\n * the TResource and TQuery type parameters populated but infer the params from\n * the supplied rule. This helps ensure that rules created for this plugin use\n * consistent types for the resource and query.\n *\n * @public\n */\nexport const makeCreatePermissionRule =\n <TResource, TQuery, TResourceType extends string>() =>\n <TParams extends PermissionRuleParams = undefined>(\n rule: PermissionRule<TResource, TQuery, TResourceType, TParams>,\n ) =>\n createPermissionRule(rule);\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 TokenManager,\n createLegacyAuthAdapters,\n} from '@backstage/backend-common';\nimport {\n AuthService,\n BackstageCredentials,\n DiscoveryService,\n PermissionsService,\n PermissionsServiceRequestOptions,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport {\n AuthorizeResult,\n PermissionClient,\n AuthorizePermissionRequest,\n AuthorizePermissionResponse,\n PolicyDecision,\n QueryPermissionRequest,\n} from '@backstage/plugin-permission-common';\n\n/**\n * A thin wrapper around\n * {@link @backstage/plugin-permission-common#PermissionClient} that allows all\n * service-to-service requests.\n * @public\n */\nexport class ServerPermissionClient implements PermissionsService {\n readonly #auth: AuthService;\n readonly #permissionClient: PermissionClient;\n readonly #permissionEnabled: boolean;\n\n static fromConfig(\n config: Config,\n options: {\n discovery: DiscoveryService;\n tokenManager: TokenManager;\n auth?: AuthService;\n },\n ) {\n const { discovery, tokenManager } = options;\n const permissionClient = new PermissionClient({ discovery, config });\n const permissionEnabled =\n config.getOptionalBoolean('permission.enabled') ?? false;\n\n if (\n permissionEnabled &&\n (tokenManager as any).isInsecureServerTokenManager\n ) {\n throw new Error(\n 'Service-to-service authentication must be configured before enabling permissions. Read more here https://backstage.io/docs/auth/service-to-service-auth',\n );\n }\n\n const { auth } = createLegacyAuthAdapters(options);\n\n return new ServerPermissionClient({\n auth,\n permissionClient,\n permissionEnabled,\n });\n }\n\n private constructor(options: {\n auth: AuthService;\n permissionClient: PermissionClient;\n permissionEnabled: boolean;\n }) {\n this.#auth = options.auth;\n this.#permissionClient = options.permissionClient;\n this.#permissionEnabled = options.permissionEnabled;\n }\n\n async authorizeConditional(\n queries: QueryPermissionRequest[],\n options?: PermissionsServiceRequestOptions,\n ): Promise<PolicyDecision[]> {\n if (await this.#shouldPermissionsBeApplied(options)) {\n return this.#permissionClient.authorizeConditional(\n queries,\n await this.#getRequestOptions(options),\n );\n }\n\n return queries.map(_ => ({ result: AuthorizeResult.ALLOW }));\n }\n\n async authorize(\n requests: AuthorizePermissionRequest[],\n options?: PermissionsServiceRequestOptions,\n ): Promise<AuthorizePermissionResponse[]> {\n if (await this.#shouldPermissionsBeApplied(options)) {\n return this.#permissionClient.authorize(\n requests,\n await this.#getRequestOptions(options),\n );\n }\n\n return requests.map(_ => ({ result: AuthorizeResult.ALLOW }));\n }\n\n async #getRequestOptions(options?: PermissionsServiceRequestOptions) {\n if (options && 'credentials' in options) {\n if (this.#auth.isPrincipal(options.credentials, 'none')) {\n return {};\n }\n\n return this.#auth.getPluginRequestToken({\n onBehalfOf: options.credentials,\n targetPluginId: 'permissions',\n });\n }\n\n return options;\n }\n\n async #shouldPermissionsBeApplied(\n options?: PermissionsServiceRequestOptions,\n ) {\n if (!this.#permissionEnabled) {\n return false;\n }\n\n let credentials: BackstageCredentials;\n if (options && 'credentials' in options) {\n credentials = options.credentials;\n } else {\n if (!options?.token) {\n return true;\n }\n try {\n credentials = await this.#auth.authenticate(options.token);\n } catch {\n return true;\n }\n }\n\n if (this.#auth.isPrincipal(credentials, 'service')) {\n return false;\n }\n return true;\n }\n}\n"],"names":["AuthorizeResult","InputError","z","Router","express","_a","zodToJsonSchema","NotImplementedError","errorHandler","PermissionClient","createLegacyAuthAdapters"],"mappings":";;;;;;;;;;;;;;;;;;AAsCa,MAAA,sBAAA,GAAyB,CAIpC,IACG,KAAA;AACH,EAAA,OAAO,CAAC,MAAiE,KAAA;AACvE,IAAO,OAAA;AAAA,MACL,MAAM,IAAK,CAAA,IAAA;AAAA,MACX,cAAc,IAAK,CAAA,YAAA;AAAA,MACnB,MAAA;AAAA,KACF,CAAA;AAAA,GACF,CAAA;AACF;;ACwBa,MAAA,sBAAA,GAAyB,CAIpC,OAUG,KAAA;AACH,EAAA,MAAM,EAAE,QA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A,6BAAA,GAA2B,eAC/B,OACA,EAAA;AACA,EAAI,IAAA,CAAC,mBAAK,kBAAoB,CAAA,EAAA;AAC5B,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AAEA,EAAI,IAAA,WAAA,CAAA;AACJ,EAAI,IAAA,OAAA,IAAW,iBAAiB,OAAS,EAAA;AACvC,IAAA,WAAA,GAAc,OAAQ,CAAA,WAAA,CAAA;AAAA,GACjB,MAAA;AACL,IAAI,IAAA,EAAC,mCAAS,KAAO,CAAA,EAAA;AACnB,MAAO,OAAA,IAAA,CAAA;AAAA,KACT;AACA,IAAI,IAAA;AACF,MAAA,WAAA,GAAc,MAAM,YAAA,CAAA,IAAA,EAAK,KAAM,CAAA,CAAA,YAAA,CAAa,QAAQ,KAAK,CAAA,CAAA;AAAA,KACnD,CAAA,MAAA;AACN,MAAO,OAAA,IAAA,CAAA;AAAA,KACT;AAAA,GACF;AAEA,EAAA,IAAI,YAAK,CAAA,IAAA,EAAA,KAAA,CAAA,CAAM,WAAY,CAAA,WAAA,EAAa,SAAS,CAAG,EAAA;AAClD,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AACA,EAAO,OAAA,IAAA,CAAA;AACT,CAAA,CAAA;AAlHK,IAAM,sBAAN,GAAA;;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { PermissionCriteria, AllOfCriteria, AnyOfCriteria, NotCriteria, PermissionRuleParams, PermissionCondition, ResourcePermission, ConditionalPolicyDecision, IdentifiedPermissionMessage, DefinitivePolicyDecision, Permission, PolicyDecision, PermissionEvaluator, QueryPermissionRequest, EvaluatorRequestOptions, AuthorizePermissionRequest, AuthorizePermissionResponse } from '@backstage/plugin-permission-common';
1
+ import { PermissionCriteria, AllOfCriteria, AnyOfCriteria, NotCriteria, PermissionRuleParams, PermissionCondition, ResourcePermission, ConditionalPolicyDecision, IdentifiedPermissionMessage, DefinitivePolicyDecision, Permission, PolicyDecision, QueryPermissionRequest, AuthorizePermissionRequest, AuthorizePermissionResponse } from '@backstage/plugin-permission-common';
2
2
  import { z } from 'zod';
3
3
  import express from 'express';
4
4
  import zodToJsonSchema from 'zod-to-json-schema';
5
5
  import { BackstageIdentityResponse } from '@backstage/plugin-auth-node';
6
- import { PluginEndpointDiscovery, TokenManager } from '@backstage/backend-common';
6
+ import { TokenManager } from '@backstage/backend-common';
7
+ import { PermissionsService, DiscoveryService, AuthService, PermissionsServiceRequestOptions } from '@backstage/backend-plugin-api';
7
8
  import { Config } from '@backstage/config';
8
9
 
9
10
  /**
@@ -354,19 +355,16 @@ interface PermissionPolicy {
354
355
  * service-to-service requests.
355
356
  * @public
356
357
  */
357
- declare class ServerPermissionClient implements PermissionEvaluator {
358
- private readonly permissionClient;
359
- private readonly tokenManager;
360
- private readonly permissionEnabled;
358
+ declare class ServerPermissionClient implements PermissionsService {
359
+ #private;
361
360
  static fromConfig(config: Config, options: {
362
- discovery: PluginEndpointDiscovery;
361
+ discovery: DiscoveryService;
363
362
  tokenManager: TokenManager;
363
+ auth?: AuthService;
364
364
  }): ServerPermissionClient;
365
365
  private constructor();
366
- authorizeConditional(queries: QueryPermissionRequest[], options?: EvaluatorRequestOptions): Promise<PolicyDecision[]>;
367
- authorize(requests: AuthorizePermissionRequest[], options?: EvaluatorRequestOptions): Promise<AuthorizePermissionResponse[]>;
368
- private isValidServerToken;
369
- private isEnabled;
366
+ authorizeConditional(queries: QueryPermissionRequest[], options?: PermissionsServiceRequestOptions): Promise<PolicyDecision[]>;
367
+ authorize(requests: AuthorizePermissionRequest[], options?: PermissionsServiceRequestOptions): Promise<AuthorizePermissionResponse[]>;
370
368
  }
371
369
 
372
370
  export { ApplyConditionsRequest, ApplyConditionsRequestEntry, ApplyConditionsResponse, ApplyConditionsResponseEntry, Condition, ConditionTransformer, Conditions, CreatePermissionIntegrationRouterResourceOptions, MetadataResponse, MetadataResponseSerializedRule, PermissionIntegrationRouterOptions, PermissionPolicy, PermissionRule, PolicyQuery, ServerPermissionClient, createConditionAuthorizer, createConditionExports, createConditionFactory, createConditionTransformer, createPermissionIntegrationRouter, createPermissionRule, isAndCriteria, isNotCriteria, isOrCriteria, makeCreatePermissionRule };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@backstage/plugin-permission-node",
3
3
  "description": "Common permission and authorization utilities for backend plugins",
4
- "version": "0.7.24",
4
+ "version": "0.7.25-next.1",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "license": "Apache-2.0",
@@ -44,12 +44,12 @@
44
44
  "start": "backstage-cli package start"
45
45
  },
46
46
  "dependencies": {
47
- "@backstage/backend-common": "^0.21.3",
48
- "@backstage/backend-plugin-api": "^0.6.13",
49
- "@backstage/config": "^1.1.1",
50
- "@backstage/errors": "^1.2.3",
51
- "@backstage/plugin-auth-node": "^0.4.8",
52
- "@backstage/plugin-permission-common": "^0.7.12",
47
+ "@backstage/backend-common": "^0.21.4-next.1",
48
+ "@backstage/backend-plugin-api": "^0.6.14-next.1",
49
+ "@backstage/config": "^1.2.0-next.1",
50
+ "@backstage/errors": "^1.2.4-next.0",
51
+ "@backstage/plugin-auth-node": "^0.4.9-next.1",
52
+ "@backstage/plugin-permission-common": "^0.7.13-next.1",
53
53
  "@types/express": "^4.17.6",
54
54
  "express": "^4.17.1",
55
55
  "express-promise-router": "^4.1.0",
@@ -57,8 +57,8 @@
57
57
  "zod-to-json-schema": "^3.20.4"
58
58
  },
59
59
  "devDependencies": {
60
- "@backstage/backend-test-utils": "^0.3.3",
61
- "@backstage/cli": "^0.25.2",
60
+ "@backstage/backend-test-utils": "^0.3.4-next.1",
61
+ "@backstage/cli": "^0.25.3-next.1",
62
62
  "@types/supertest": "^2.0.8",
63
63
  "msw": "^1.0.0",
64
64
  "supertest": "^6.1.3"