-
Notifications
You must be signed in to change notification settings - Fork 7
/
claims.service.e2e.ts
1333 lines (1235 loc) · 43.1 KB
/
claims.service.e2e.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import jsonwebtoken from 'jsonwebtoken';
import {
IRoleDefinitionV2,
IssuerFields,
PreconditionType,
} from '@energyweb/credential-governance';
import { Methods, Chain } from '@ew-did-registry/did';
import { addressOf } from '@ew-did-registry/did-ethr-resolver';
import { KeyTags } from '@ew-did-registry/did-resolver-interface';
import {
CredentialStatusPurpose,
VerifiablePresentation,
Credential,
StatusListEntryType,
StatusList2021Entry,
} from '@ew-did-registry/credentials-interface';
import { BigNumber, providers, utils, Wallet } from 'ethers';
import nock from 'nock';
import {
AssetsService,
ClaimsService,
DomainsService,
ERROR_MESSAGES,
initWithPrivateKeySigner,
ProviderType,
RegistrationTypes,
SignerService,
chainConfigs,
DidRegistry,
MessagingService,
IClaimIssuance,
SignerT,
Claim,
RoleCredentialSubject,
CacheClient,
VerifiableCredentialsServiceBase,
getVerifiableCredentialsService,
setLogger,
ConsoleLogger,
LogLevel,
} from '../src';
import { replenish, root, rpcUrl, setupENS } from './utils/setup-contracts';
import { ClaimManager__factory } from '../ethers/factories/ClaimManager__factory';
import { ProofVerifier } from '@ew-did-registry/claims';
import { ClaimManager } from '../ethers/ClaimManager';
import { RoleEIP191JWT } from '@energyweb/vc-verification';
import { JwtPayload } from '@ew-did-registry/jwt';
import { shutDownIpfsDaemon, spawnIpfsDaemon } from './utils/setup-ipfs';
const { namehash, id } = utils;
const provider = new providers.JsonRpcProvider(rpcUrl);
const staticIssuer = Wallet.createRandom().connect(provider);
const staticIssuerDID = `did:${Methods.Erc1056}:${Chain.VOLTA}:${staticIssuer.address}`;
const dynamicIssuer = Wallet.createRandom().connect(provider);
const dynamicIssuerDID = `did:${Methods.Erc1056}:${Chain.VOLTA}:${dynamicIssuer.address}`;
const projectInstallerCandidate = Wallet.createRandom().connect(provider);
const projectInstallerCandidateDID = `did:${Methods.Erc1056}:${Chain.VOLTA}:${projectInstallerCandidate.address}`;
const rootOwner = Wallet.createRandom().connect(provider);
const rootOwnerDID = `did:${Methods.Erc1056}:${Chain.VOLTA}:${rootOwner.address}`;
const roleName1 = 'myrole1';
const roleName2 = 'myrole2';
const roleName3 = 'myrole3';
const roleName4 = 'myrole4';
const roleName5 = 'myrole5';
const verifyVcRole = 'verifyVcRole';
const verifyVcRole2 = 'verifyVcRole2';
const verifyOffChainClaimRole = 'verifyOnChain';
const resolveVC = 'resolvevc';
const verifyResolvedVcExpired = 'vcResolvedExpired';
const eip191JwtExpired = 'eip191JwtExpired';
const vcExpired = 'vcExpired';
const electrician = 'electrician';
const projectElectrician = 'projectElectrician';
const projectInstaller = 'projectInstaller';
const namespace = root;
const version = 1;
const baseRoleDef = {
roleType: 'org',
fields: [],
issuerFields: [],
enrolmentPreconditions: [],
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
version,
metadata: {},
revoker: { revokerType: 'DID', did: [staticIssuerDID] },
};
const roles: Record<string, IRoleDefinitionV2> = {
[`${roleName1}.${root}`]: { ...baseRoleDef, roleName: roleName1 },
[`${roleName2}.${root}`]: {
...baseRoleDef,
roleName: roleName2,
issuer: { issuerType: 'ROLE', roleName: `${roleName1}.${root}` },
},
[`${roleName3}.${root}`]: {
...baseRoleDef,
roleName: roleName3,
enrolmentPreconditions: [
{ type: PreconditionType.Role, conditions: [`${roleName1}.${root}`] },
],
},
[`${roleName4}.${root}`]: {
...baseRoleDef,
roleName: roleName4,
issuer: { issuerType: 'ROLE', roleName: `${roleName1}.${root}` },
},
[`${roleName5}.${root}`]: {
...baseRoleDef,
roleName: roleName5,
defaultValidityPeriod: 1000,
},
[`${verifyVcRole}.${root}`]: {
...baseRoleDef,
roleName: verifyVcRole,
issuer: { issuerType: 'DID', did: [rootOwnerDID] },
},
[`${resolveVC}.${root}`]: {
...baseRoleDef,
roleName: resolveVC,
},
[`${verifyVcRole2}.${root}`]: {
...baseRoleDef,
roleName: verifyVcRole2,
},
[`${verifyOffChainClaimRole}.${root}`]: {
...baseRoleDef,
roleName: verifyOffChainClaimRole,
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
},
[`${verifyResolvedVcExpired}.${root}`]: {
...baseRoleDef,
roleName: verifyResolvedVcExpired,
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
},
[`${vcExpired}.${root}`]: {
...baseRoleDef,
roleName: vcExpired,
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
},
[`${eip191JwtExpired}.${root}`]: {
...baseRoleDef,
roleName: eip191JwtExpired,
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
},
[`${electrician}.${root}`]: {
...baseRoleDef,
roleName: electrician,
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
},
[`${projectElectrician}.${root}`]: {
...baseRoleDef,
roleName: projectElectrician,
issuer: { issuerType: 'DID', did: [projectInstallerCandidateDID] },
enrolmentPreconditions: [
{ type: PreconditionType.Role, conditions: [`${electrician}.${root}`] },
],
},
[`${projectInstaller}.${root}`]: {
...baseRoleDef,
roleName: projectInstaller,
issuer: { issuerType: 'DID', did: [staticIssuerDID] },
},
};
const mockGetRoleDefinition = jest
.fn()
.mockImplementation((namespace: string) => {
return roles[namespace];
});
const mockCachedDocument = jest.fn().mockImplementation((did: string) => {
return {
publicKey: [
{ id: `did:${Methods.Erc1056}:${Chain.VOLTA}:${did}-${KeyTags.OWNER}` },
],
}; // all documents are created
});
const getClamsBySubjectInitMock: (did: string) => Partial<Claim>[] = () => [];
const mockGetCachedOwnedAssets = jest.fn();
const mockGetAssetById = jest.fn();
const mockGetClaimsBySubject = jest.fn();
const mockRequestClaim = jest.fn();
const mockIssueClaim = jest.fn();
const mockRejectClaim = jest.fn();
const mockGetAllowedRoles = jest.fn();
jest.mock('../src/modules/cache-client/cache-client.service', () => {
return {
CacheClient: jest.fn().mockImplementation(() => {
return {
getRoleDefinition: mockGetRoleDefinition,
getDidDocument: mockCachedDocument,
getAssetById: mockGetAssetById,
getOwnedAssets: mockGetCachedOwnedAssets,
getClaimsBySubject: mockGetClaimsBySubject,
init: jest.fn(),
login: jest.fn(),
requestClaim: mockRequestClaim,
issueClaim: mockIssueClaim,
rejectClaim: mockRejectClaim,
getAllowedRolesByIssuer: mockGetAllowedRoles,
addStatusToCredential: (
credential: Credential<RoleCredentialSubject>
): Credential<RoleCredentialSubject> => {
return {
...credential,
credentialStatus: {
id: `https://energyweb.org/credential/${id(
JSON.stringify(credential)
)}#list`,
type: StatusListEntryType.Entry2021,
statusPurpose: CredentialStatusPurpose.REVOCATION,
statusListIndex: '1',
statusListCredential: `https://identitycache.org/v1/status-list/${credential.id}`,
},
};
},
};
}),
};
});
MessagingService.create = (signerService: SignerService) =>
Promise.resolve(new MessagingService(signerService));
jest.mock('../src/modules/messaging/messaging.service', () => {
return {
MessagingService: jest.fn().mockImplementation(() => {
return { publish: jest.fn() };
}),
};
});
describe('Сlaim tests', () => {
let claimsService: ClaimsService;
let signerService: SignerService;
let assetsService: AssetsService;
let domainsService: DomainsService;
let claimManager: ClaimManager;
let didRegistry: DidRegistry;
let verifiableCredentialsService: VerifiableCredentialsServiceBase;
beforeEach(async () => {
jest.clearAllMocks();
mockGetClaimsBySubject.mockImplementation(getClamsBySubjectInitMock);
await replenish(await staticIssuer.getAddress());
await replenish(await rootOwner.getAddress());
await replenish(await dynamicIssuer.getAddress());
await replenish(await projectInstallerCandidate.getAddress());
await setupENS(await rootOwner.getAddress());
let connectToCacheServer;
({ signerService, connectToCacheServer } = await initWithPrivateKeySigner(
rootOwner.privateKey,
rpcUrl
));
await signerService.publicKeyAndIdentityToken();
const chainId = signerService.chainId;
claimManager = new ClaimManager__factory(rootOwner).attach(
chainConfigs()[chainId].claimManagerAddress
);
let connectToDidRegistry;
({ domainsService, connectToDidRegistry, assetsService } =
await connectToCacheServer());
await domainsService.createRole({
roleName: roleName1,
namespace,
data: roles[`${roleName1}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: roleName4,
namespace,
data: roles[`${roleName4}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: roleName5,
namespace,
data: roles[`${roleName5}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: verifyVcRole,
namespace,
data: roles[`${verifyVcRole}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: verifyVcRole2,
namespace,
data: roles[`${verifyVcRole2}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: verifyOffChainClaimRole,
namespace,
data: roles[`${verifyOffChainClaimRole}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: resolveVC,
namespace,
data: roles[`${resolveVC}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: verifyResolvedVcExpired,
namespace,
data: roles[`${verifyResolvedVcExpired}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: vcExpired,
namespace,
data: roles[`${vcExpired}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: eip191JwtExpired,
namespace,
data: roles[`${eip191JwtExpired}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: electrician,
namespace,
data: roles[`${electrician}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: projectElectrician,
namespace,
data: roles[`${projectElectrician}.${root}`],
returnSteps: false,
});
await domainsService.createRole({
roleName: projectInstaller,
namespace,
data: roles[`${projectInstaller}.${root}`],
returnSteps: false,
});
({ didRegistry, claimsService } = await connectToDidRegistry(
await spawnIpfsDaemon()
));
mockGetAllowedRoles.mockImplementation(async (issuer) => {
const roleDefs = Object.values(roles);
const isRoleIssuerOfRole = await Promise.all(
roleDefs.map(
(r) =>
r.issuer.roleName &&
claimsService.hasOnChainRole(issuer, r.issuer.roleName, version)
)
);
const allowedRoles = roleDefs
.filter((r, i) => {
return (
(r.issuer.issuerType === 'DID' && r.issuer.did?.includes(issuer)) ||
(r.issuer.issuerType === 'ROLE' && isRoleIssuerOfRole[i])
);
})
.map((r) => ({ ...r, namespace: `${r.roleName}.${root}` }));
return allowedRoles;
});
Reflect.set(didRegistry, '_cacheClient', undefined);
setLogger(new ConsoleLogger(LogLevel.warn));
const cacheClient = new CacheClient(signerService);
verifiableCredentialsService = await getVerifiableCredentialsService(
signerService,
cacheClient
);
});
afterEach(async () => {
await shutDownIpfsDaemon();
});
describe('Role claim tests', () => {
async function enrolAndIssue(
requestSigner: Required<SignerT>,
issueSigner: Required<SignerT>,
{
subjectDID,
claimType,
registrationTypes = [RegistrationTypes.OnChain],
publishOnChain = true,
issuerFields,
expirationTimestamp,
}: {
subjectDID: string;
claimType: string;
registrationTypes?: RegistrationTypes[];
publishOnChain?: boolean;
issuerFields?: Record<string, string | number>[];
expirationTimestamp?: number;
}
) {
await signerService.connect(requestSigner, ProviderType.PrivateKey);
const requesterDID = signerService.did;
const requestorFields = [{ key: 'temperature', value: 36 }];
await claimsService.createClaimRequest({
claim: {
claimType,
claimTypeVersion: version,
requestorFields,
},
registrationTypes,
subject: subjectDID,
});
const [message] = mockRequestClaim.mock.calls.pop();
await signerService.connect(issueSigner, ProviderType.PrivateKey);
const issuerDID = signerService.did;
await claimsService.issueClaimRequest({
publishOnChain,
issuerFields,
expirationTimestamp,
...message,
});
const [, issuedClaim] = <[string, Required<IClaimIssuance>]>(
mockIssueClaim.mock.calls.pop()
);
const currentGetClaimsBySubjectMock =
mockGetClaimsBySubject.getMockImplementation() as jest.Mock;
mockGetClaimsBySubject.mockImplementation((did) =>
[...currentGetClaimsBySubjectMock(did)].concat(
did === subjectDID
? [
{
claimType,
claimTypeVersion: version,
issuedToken: issuedClaim.issuedToken,
},
]
: []
)
);
const {
issuedToken,
requester,
claimIssuer,
onChainProof,
acceptedBy,
vp,
} = issuedClaim;
const roleDefinitionValidityPeriod =
roles[claimType].defaultValidityPeriod;
if (registrationTypes.includes(RegistrationTypes.OffChain)) {
expect(issuedToken).toBeDefined();
const { credentialStatus } = (await didRegistry.decodeJWTToken({
token: issuedToken,
})) as { [key: string]: StatusList2021Entry };
expect(credentialStatus).toBeDefined;
expect(credentialStatus.type).toEqual(StatusListEntryType.Entry2021);
expect(vp).toBeDefined();
const vpObject = JSON.parse(vp) as VerifiablePresentation;
expect(vpObject.verifiableCredential).toHaveLength(1);
expect(vpObject.verifiableCredential[0].credentialSubject).toEqual({
id: subjectDID,
role: {
namespace: claimType,
version: version.toString(),
},
issuerFields: issuerFields || [],
});
expect(vpObject.verifiableCredential[0].issuer).toEqual(
signerService.didHex
);
expirationTimestamp &&
expect(vpObject.verifiableCredential[0].expirationDate).toEqual(
new Date(expirationTimestamp).toISOString()
);
if (roleDefinitionValidityPeriod && !expirationTimestamp) {
expect(vpObject.verifiableCredential[0].expirationDate).toEqual(
new Date(Date.now() + roleDefinitionValidityPeriod).toISOString()
);
}
expect(vpObject.holder).toEqual(signerService.didHex);
const { claimData, signer, did, exp } =
(await didRegistry.decodeJWTToken({
token: issuedToken,
})) as { [key: string]: string };
expect(claimData).toEqual({
claimType,
claimTypeVersion: version,
issuerFields,
requestorFields,
});
expirationTimestamp && expect(exp).toEqual(Math.floor(expirationTimestamp / 1000));
expect(claimData).not.toContain({
fields: [{ key: 'temperature', value: 36 }],
});
expect(signer).toBe(issuerDID);
expect(did).toBe(requesterDID);
}
expect(requester).toEqual(requesterDID);
expect(claimIssuer).toEqual([issuerDID]);
if (registrationTypes.includes(RegistrationTypes.OnChain)) {
expect(onChainProof).toHaveLength(132);
if (expirationTimestamp || roleDefinitionValidityPeriod) {
const filter = claimManager.filters.RoleRegistered();
const logs = await claimManager.queryFilter(filter);
logs.forEach((log) => {
const parsedLog = claimManager.interface.parseLog(log);
const args = parsedLog.args as unknown as {
subject: string;
role: string;
version: BigNumber;
expiry: BigNumber;
issuer: string;
};
if (
args.subject === addressOf(subjectDID) &&
args.role === namehash(claimType)
) {
expirationTimestamp &&
expect(args.expiry.toNumber()).toEqual(
Math.floor(expirationTimestamp / 1000)
);
}
});
}
}
expect(acceptedBy).toBe(issuerDID);
return issuedClaim;
}
async function issueWithoutRequest(
issueSigner: Required<SignerT>,
{
subjectDID,
claimType,
registrationTypes = [RegistrationTypes.OnChain],
issuerFields,
}: {
subjectDID: string;
claimType: string;
registrationTypes?: RegistrationTypes[];
publishOnChain?: boolean;
issuerFields?: { key: string; value: string | number }[];
}
) {
await signerService.connect(issueSigner, ProviderType.PrivateKey);
const requesterDID = subjectDID;
const issuerDID = signerService.did;
const requestorFields = [{ key: 'temperature', value: 36 }];
await claimsService.issueClaim({
subject: subjectDID,
registrationTypes,
claim: {
claimType,
claimTypeVersion: version,
issuerFields: issuerFields || [],
},
});
const [did, issuedClaim] = <[string, Required<IClaimIssuance>]>(
mockIssueClaim.mock.calls.pop()
);
expect(did).toBe(issuerDID);
const { issuedToken, requester, claimIssuer, acceptedBy } = issuedClaim;
if (registrationTypes.includes(RegistrationTypes.OffChain)) {
expect(issuedToken).toBeDefined();
const { claimData, signer, did } = (await didRegistry.decodeJWTToken({
token: issuedToken,
})) as { [key: string]: string };
expect(claimData).toEqual({
claimType,
claimTypeVersion: version,
issuerFields,
requestorFields,
});
expect(signer).toBe(issuerDID);
expect(did).toBe(requesterDID);
}
expect(requester).toEqual(subjectDID);
expect(claimIssuer).toEqual([issuerDID]);
expect(acceptedBy).toBe(issuerDID);
return issuedClaim;
}
test('enrollment by issuer of type DID', async () => {
const requester = rootOwner;
const issuer = staticIssuer;
const subjectDID = rootOwnerDID;
const role = `${roleName1}.${root}`;
const claimType = `${roleName1}.${root}`;
expect(
await claimsService.hasOnChainRole(rootOwnerDID, role, version)
).toBe(false);
await enrolAndIssue(requester, issuer, {
subjectDID,
claimType,
});
expect(
await claimManager.hasRole(
addressOf(subjectDID),
namehash(role),
version
)
).toBe(true);
expect(
await claimsService.hasOnChainRole(subjectDID, role, version)
).toBe(true);
});
test('asset enrollment by issuer of type DID', async () => {
mockGetAssetById.mockImplementationOnce(({ id }: { id: string }) => ({
id,
}));
await signerService.connect(rootOwner, ProviderType.PrivateKey);
const assetAddress = await assetsService.registerAsset();
const assetDID = `did:${Methods.Erc1056}:${Chain.VOLTA}:${assetAddress}`;
await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: assetDID,
claimType: `${roleName1}.${root}`,
});
return expect(
await claimsService.hasOnChainRole(
assetDID,
`${roleName1}.${root}`,
version
)
).toBe(true);
});
test('enrollment by issuer of type ROLE', async () => {
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await domainsService.createRole({
roleName: roleName2,
namespace,
data: roles[`${roleName2}.${root}`],
returnSteps: false,
});
await enrolAndIssue(dynamicIssuer, staticIssuer, {
subjectDID: dynamicIssuerDID,
claimType: `${roleName1}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain, // role type issuer should have offchain claim
],
issuerFields: [],
});
expect(
await claimManager.hasRole(
addressOf(dynamicIssuerDID),
namehash(`${roleName1}.${root}`),
version
)
);
await enrolAndIssue(rootOwner, dynamicIssuer, {
subjectDID: rootOwnerDID,
claimType: `${roleName2}.${root}`,
});
return expect(
await claimsService.hasOnChainRole(
rootOwnerDID,
`${roleName2}.${root}`,
version
)
).toBe(true);
});
test('should enrol when prerequisites are met', async () => {
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await domainsService.createRole({
roleName: roleName3,
namespace,
data: roles[`${roleName3}.${root}`],
returnSteps: false,
});
const roleOneIssuance = await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType: `${roleName1}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain,
],
publishOnChain: true,
issuerFields: [],
});
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await claimsService.publishPublicClaim({
claim: { token: roleOneIssuance.issuedToken },
});
const roleTwoIssuance = await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType: `${roleName3}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain,
],
publishOnChain: true,
issuerFields: [],
});
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await claimsService.publishPublicClaim({
claim: { token: roleTwoIssuance.issuedToken },
});
return expect(
await claimsService.hasOnChainRole(
rootOwnerDID,
`${roleName3}.${root}`,
version
)
).toBe(true);
});
test('should enrol when prerequisite role is met and the issuer is not the issuer of the prerequisite role', async () => {
//Root Owner enrols to 'Electrician' role
const enrolToElectrician = await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType: `${electrician}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain,
],
publishOnChain: true,
issuerFields: [],
});
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await claimsService.publishPublicClaim({
claim: { token: enrolToElectrician.issuedToken },
});
//Project Installer Candidate enrols to 'Project Installer' role
const enrolToProjectInstaller = await enrolAndIssue(
projectInstallerCandidate,
staticIssuer,
{
subjectDID: projectInstallerCandidateDID,
claimType: `${projectInstaller}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain,
],
publishOnChain: true,
issuerFields: [],
}
);
await signerService.connect(
projectInstallerCandidate,
ProviderType.PrivateKey
);
await claimsService.publishPublicClaim({
claim: { token: enrolToProjectInstaller.issuedToken },
});
//Root Owner enrols to 'Project Electrician' role. 'Electrician' is pre-requisite role; Project Installer is issuer of 'Project Electrician' role, not issuer of 'Electrician' role
const enrolToProjectElectrician = await enrolAndIssue(
rootOwner,
projectInstallerCandidate,
{
subjectDID: rootOwnerDID,
claimType: `${projectElectrician}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain,
],
publishOnChain: true,
issuerFields: [],
}
);
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await claimsService.publishPublicClaim({
claim: { token: enrolToProjectElectrician.issuedToken },
});
//Expect Root Owner to have role of Project Electrician
return expect(
await claimsService.hasOnChainRole(
rootOwnerDID,
`${projectElectrician}.${root}`,
version
)
).toBe(true);
});
test('should reject to enrol when prerequisites are not met', async () => {
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await domainsService.createRole({
roleName: roleName3,
namespace,
data: roles[`${roleName3}.${root}`],
returnSteps: false,
});
return expect(
enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType: `${roleName3}.${root}`,
})
).rejects.toEqual(new Error(ERROR_MESSAGES.ROLE_PREREQUISITES_NOT_MET));
});
test('enrollment with credential/claim time expiration', async () => {
const requester = rootOwner;
const issuer = staticIssuer;
const subjectDID = rootOwnerDID;
const claimType = `${roleName1}.${root}`;
await enrolAndIssue(requester, issuer, {
subjectDID,
claimType,
expirationTimestamp: Date.now() + 100000,
});
expect(
await claimsService.hasOnChainRole(subjectDID, claimType, version)
).toBe(true);
});
test('enrolment should fail if issuer authoritative credential has expired', async () => {
await signerService.connect(rootOwner, ProviderType.PrivateKey);
await domainsService.createRole({
roleName: roleName2,
namespace,
data: roles[`${roleName2}.${root}`],
returnSteps: false,
});
const res = await enrolAndIssue(dynamicIssuer, staticIssuer, {
subjectDID: dynamicIssuerDID,
claimType: `${roleName1}.${root}`,
registrationTypes: [
RegistrationTypes.OnChain,
RegistrationTypes.OffChain, // role type issuer should have offchain claim
],
issuerFields: [],
expirationTimestamp: Date.now() + 7000,
});
await signerService.connect(dynamicIssuer, ProviderType.PrivateKey);
await claimsService.publishPublicClaim({
claim: { token: res.issuedToken },
});
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
await delay(8000);
return expect(
enrolAndIssue(rootOwner, dynamicIssuer, {
subjectDID: rootOwnerDID,
claimType: `${roleName2}.${root}`,
expirationTimestamp: Date.now() + 100000,
registrationTypes: [RegistrationTypes.OffChain],
})
).rejects.toEqual(new Error('Issuer credential has expired'));
});
test('enrollment with credential/claim default time expiration from role definition', async () => {
const requester = rootOwner;
const issuer = staticIssuer;
const subjectDID = rootOwnerDID;
const claimType = `${roleName5}.${root}`;
await enrolAndIssue(requester, issuer, {
subjectDID,
claimType,
});
expect(
await claimsService.hasOnChainRole(subjectDID, claimType, version)
).toBe(true);
});
describe('Publishing onchain', () => {
const registrationTypes = [RegistrationTypes.OnChain];
const claimType = `${roleName1}.${root}`;
const role1Claim = {
claimType,
claimTypeVersion: version,
isAccepted: true,
subject: rootOwnerDID,
};
test('should be able to issue and publish onchain', async () => {
await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType,
registrationTypes,
publishOnChain: true,
});
expect(
await claimsService.hasOnChainRole(rootOwnerDID, claimType, version)
).toBe(true);
});
test('should be able to issue and publish onchain without request', async () => {
const claim = await issueWithoutRequest(staticIssuer, {
subjectDID: rootOwnerDID,
claimType,
registrationTypes,
});
expect(claim.onChainProof).toHaveLength(132);
await signerService.connect(rootOwner, ProviderType.PrivateKey);
const mockedClaim = {
claimType,
isApproved: true,
onChainProof: claim.onChainProof,
claimTypeVersion: version,
acceptedBy: claim.acceptedBy,
subject: rootOwnerDID,
};
mockGetClaimsBySubject
.mockReset()
.mockImplementationOnce(() => [mockedClaim]);
await claimsService.publishPublicClaim({
claim: { claimType },
registrationTypes,
});
expect(
await claimsService.hasOnChainRole(rootOwnerDID, claimType, version)
).toBe(true);
});
test('should be able to issue without publishing onchain', async () => {
mockGetClaimsBySubject.mockImplementationOnce(() => [role1Claim]);
await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType,
registrationTypes,
publishOnChain: false,
});
expect(
await claimsService.hasOnChainRole(rootOwnerDID, claimType, version)
).toBe(false);
});
test('should be able to issue when role registered onchain', async () => {
await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType,
registrationTypes: [
RegistrationTypes.OffChain,
RegistrationTypes.OnChain,
],
publishOnChain: true,
});
expect(
await claimsService.hasOnChainRole(rootOwnerDID, claimType, version)
).toBe(true);
await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType,
registrationTypes: [
RegistrationTypes.OffChain,
RegistrationTypes.OnChain,
],
publishOnChain: true,
});
});
test('should be able to issue without publishing onchain', async () => {
await enrolAndIssue(rootOwner, staticIssuer, {
subjectDID: rootOwnerDID,
claimType,
registrationTypes: [
RegistrationTypes.OffChain,
RegistrationTypes.OnChain,
],
publishOnChain: false,
});
expect(
await claimsService.hasOnChainRole(rootOwnerDID, claimType, version)