From 0a18c1cda47ebd0ac9a1a7b26858afafc545c02d Mon Sep 17 00:00:00 2001 From: Artur Sudnik-Hrynkiewicz Date: Mon, 14 Jun 2021 13:23:03 +0200 Subject: [PATCH] tests: access token verifiedRoles check --- .../origin-backend/test/did-user.e2e-spec.ts | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/origin-backend/test/did-user.e2e-spec.ts b/packages/origin-backend/test/did-user.e2e-spec.ts index 187d967f13..e2b97feed1 100644 --- a/packages/origin-backend/test/did-user.e2e-spec.ts +++ b/packages/origin-backend/test/did-user.e2e-spec.ts @@ -4,7 +4,7 @@ import { DatabaseService } from '@energyweb/origin-backend-utils'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { expect } from 'chai'; import request from 'supertest'; -import { IAM, setCacheClientOptions, setChainConfig } from 'iam-client-lib'; +import { IAM, setCacheClientOptions, setChainConfig, ENSNamespaceTypes } from 'iam-client-lib'; import { OrganizationService } from '../src/pods/organization/organization.service'; import { TUserBaseEntity, UserService } from '../src/pods/user'; @@ -125,11 +125,24 @@ describe('DID user e2e tests', function () { throw new Error('precondition failed'); }); - const accessTokenDecoded = jwt.verify(accessToken, process.env.JWT_SECRET); + const accessTokenDecoded = jwt.verify(accessToken, process.env.JWT_SECRET) as { + did: string; + verifiedRoles: { name: string; namespace: string }[]; + }; - expect(accessTokenDecoded).to.contain.keys(['verifiedRoles']); + expect(accessTokenDecoded).to.contain.keys(['did', 'verifiedRoles']); + expect(accessTokenDecoded.verifiedRoles).to.be.an('array'); - // TODO: implement check if roles are valid + const onChainRoles = (await getDidRoles(iam, did)).sort(), + accessTokenRoles = accessTokenDecoded.verifiedRoles + .map((r) => r.namespace) + .sort(); + + accessTokenRoles.forEach((accTokenRole) => + expect(onChainRoles).to.include(accTokenRole) + ); + + // TODO: implement check if all expected on-chain roles are included in the access token }); describe('corresponding user table record', function () { @@ -186,3 +199,19 @@ async function loginDidUser(app: any, identityToken: string): Promise { return res.body.accessToken; } + +/** + * Returns an array of roles for a given DID, + * extracted from claims (IAM.getUserClaims) + */ +async function getDidRoles(iam: IAM, did: string): Promise { + const userClaims = await iam.getUserClaims({ did }); + + return userClaims + .filter((claim) => !!claim.claimType) // getting only claims with claimType property + .map((claim) => claim.claimType) + .filter((claimType) => { + const arr = claimType.split('.'); + return arr.length > 1 && arr[1] === ENSNamespaceTypes.Roles; + }); +}