From 02d2b8681f24b489d7ff68543170600c6c218c3a Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sun, 14 Feb 2021 19:50:41 +0100 Subject: [PATCH] auth-backend: add getEntityClaims helper that figures out the claims needed to represent an entity Signed-off-by: Patrik Oldsberg --- .../auth-backend/src/lib/catalog/helpers.ts | 49 +++++++++++++++++++ plugins/auth-backend/src/lib/catalog/index.ts | 1 + 2 files changed, 50 insertions(+) create mode 100644 plugins/auth-backend/src/lib/catalog/helpers.ts diff --git a/plugins/auth-backend/src/lib/catalog/helpers.ts b/plugins/auth-backend/src/lib/catalog/helpers.ts new file mode 100644 index 0000000000..a73b797368 --- /dev/null +++ b/plugins/auth-backend/src/lib/catalog/helpers.ts @@ -0,0 +1,49 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + UserEntity, + serializeEntityRef, + RELATION_MEMBER_OF, +} from '@backstage/catalog-model'; +import { TokenParams } from '../../identity'; + +export function getEntityClaims(entity: UserEntity): TokenParams['claims'] { + const userRef = serializeEntityRef(entity); + if (typeof userRef !== 'string') { + throw new Error( + `Failed to serialize user entity ref, ${JSON.stringify(userRef)}`, + ); + } + + const membershipRefs = + entity.relations + ?.filter(r => r.type === RELATION_MEMBER_OF) + .map(r => { + const ref = serializeEntityRef(r.target); + if (typeof ref !== 'string') { + throw new Error( + `Failed to serialize relation entity ref, ${JSON.stringify(ref)}`, + ); + } + return ref; + }) ?? []; + + return { + sub: userRef, + ent: [userRef, ...membershipRefs], + }; +} diff --git a/plugins/auth-backend/src/lib/catalog/index.ts b/plugins/auth-backend/src/lib/catalog/index.ts index f15469668f..fbd58081e3 100644 --- a/plugins/auth-backend/src/lib/catalog/index.ts +++ b/plugins/auth-backend/src/lib/catalog/index.ts @@ -15,3 +15,4 @@ */ export { CatalogIdentityClient } from './CatalogIdentityClient'; +export { getEntityClaims } from './helpers';