@icure/api 8.0.19 → 8.0.20
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/icc-x-api/crypto/ExtendedApisUtilsImpl.js +39 -27
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-x-api/crypto/legacy-metadata-migration-test.d.ts +1 -0
- package/test/icc-x-api/crypto/legacy-metadata-migration-test.js +369 -0
- package/test/icc-x-api/crypto/legacy-metadata-migration-test.js.map +1 -0
- package/test/utils/test_utils.d.ts +2 -0
- package/test/utils/test_utils.js +2 -1
- package/test/utils/test_utils.js.map +1 -1
|
@@ -258,13 +258,16 @@ class ExtendedApisUtilsImpl {
|
|
|
258
258
|
}
|
|
259
259
|
makeMigrationRequestsIfNeeded(entity, userRequestsForEntity) {
|
|
260
260
|
return __awaiter(this, void 0, void 0, function* () {
|
|
261
|
-
const hierarchy =
|
|
261
|
+
const hierarchy = this.useParentKeys
|
|
262
|
+
? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()
|
|
263
|
+
: [yield this.dataOwnerApi.getCurrentDataOwnerId()];
|
|
262
264
|
const legacySecretIds = yield (0, collection_utils_1.asyncGeneratorToArray)(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy));
|
|
263
265
|
const legacyEncryptionKeys = yield (0, collection_utils_1.asyncGeneratorToArray)(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy));
|
|
264
266
|
const legacyOwningEntityIds = yield (0, collection_utils_1.asyncGeneratorToArray)(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy));
|
|
265
267
|
const res = {};
|
|
268
|
+
const selfId = yield this.dataOwnerApi.getCurrentDataOwnerId();
|
|
266
269
|
for (const hierarchyMember of hierarchy) {
|
|
267
|
-
const hierarchyMemberMigration = yield this.makeMigrationRequestForMemberOfHierarchy(entity, hierarchyMember, userRequestsForEntity[hierarchyMember], legacySecretIds, legacyEncryptionKeys, legacyOwningEntityIds);
|
|
270
|
+
const hierarchyMemberMigration = yield this.makeMigrationRequestForMemberOfHierarchy(entity, selfId, hierarchyMember, userRequestsForEntity[hierarchyMember], legacySecretIds, legacyEncryptionKeys, legacyOwningEntityIds);
|
|
268
271
|
if (hierarchyMemberMigration) {
|
|
269
272
|
res[hierarchyMember] = hierarchyMemberMigration;
|
|
270
273
|
}
|
|
@@ -272,47 +275,49 @@ class ExtendedApisUtilsImpl {
|
|
|
272
275
|
return res;
|
|
273
276
|
});
|
|
274
277
|
}
|
|
275
|
-
makeMigrationRequestForMemberOfHierarchy(entity,
|
|
276
|
-
var _a, _b, _c
|
|
278
|
+
makeMigrationRequestForMemberOfHierarchy(entity, selfId, currMemberId, userRequestForDelegate, legacySecretIds, legacyEncryptionKeys, legacyOwningEntityIds) {
|
|
279
|
+
var _a, _b, _c;
|
|
277
280
|
return __awaiter(this, void 0, void 0, function* () {
|
|
278
|
-
|
|
279
|
-
const
|
|
281
|
+
// This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.
|
|
282
|
+
const subHierarchy = this.useParentKeys ? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId];
|
|
283
|
+
const subHierarchySet = new Set(subHierarchy);
|
|
284
|
+
const legacyAccess = selfId === entity.entity.id && currMemberId === selfId
|
|
280
285
|
? AccessLevel.WRITE
|
|
281
|
-
: yield this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity,
|
|
286
|
+
: yield this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy);
|
|
282
287
|
if (!legacyAccess)
|
|
283
288
|
return undefined;
|
|
284
|
-
const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.
|
|
285
|
-
const selfLegacyEncryptionKeys = legacyEncryptionKeys
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const
|
|
289
|
+
const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted);
|
|
290
|
+
const selfLegacyEncryptionKeys = legacyEncryptionKeys
|
|
291
|
+
.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))
|
|
292
|
+
.map((x) => x.decrypted);
|
|
293
|
+
const selfLegacyOwningEntityIds = legacyOwningEntityIds
|
|
294
|
+
.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))
|
|
295
|
+
.map((x) => x.decrypted);
|
|
289
296
|
let missingSecretIds = [];
|
|
290
297
|
let missingEncryptionKeys = [];
|
|
291
298
|
let missingOwningEntityIds = [];
|
|
292
299
|
if (selfLegacySecretIds.length > 0) {
|
|
293
|
-
const currentSecretIds = new Set((yield (0, collection_utils_1.asyncGeneratorToArray)(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [
|
|
300
|
+
const currentSecretIds = new Set((yield (0, collection_utils_1.asyncGeneratorToArray)(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [currMemberId]))).map((x) => x.decrypted));
|
|
294
301
|
missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x));
|
|
295
302
|
}
|
|
296
303
|
if (selfLegacyEncryptionKeys.length > 0) {
|
|
297
|
-
const currentEncryptionKeys = new Set((yield (0, collection_utils_1.asyncGeneratorToArray)(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [
|
|
304
|
+
const currentEncryptionKeys = new Set((yield (0, collection_utils_1.asyncGeneratorToArray)(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [currMemberId]))).map((x) => x.decrypted));
|
|
298
305
|
missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x));
|
|
299
306
|
}
|
|
300
307
|
if (selfLegacyOwningEntityIds.length > 0) {
|
|
301
|
-
const currentOwningEntityIds = new Set((yield (0, collection_utils_1.asyncGeneratorToArray)(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [
|
|
308
|
+
const currentOwningEntityIds = new Set((yield (0, collection_utils_1.asyncGeneratorToArray)(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [currMemberId]))).map((x) => x.decrypted));
|
|
302
309
|
missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x));
|
|
303
310
|
}
|
|
304
|
-
|
|
311
|
+
const mustCreateRootDelegation = selfId === entity.entity.id && currMemberId === selfId && !(yield this.secDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy));
|
|
312
|
+
if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {
|
|
305
313
|
let requestedPermissions;
|
|
306
|
-
if (
|
|
314
|
+
if (currMemberId === selfId) {
|
|
307
315
|
requestedPermissions = RequestedPermissionInternal.ROOT;
|
|
308
316
|
}
|
|
309
|
-
else if (legacyAccess === AccessLevel.WRITE) {
|
|
310
|
-
requestedPermissions = RequestedPermissionInternal.FULL_WRITE;
|
|
311
|
-
}
|
|
312
317
|
else {
|
|
313
|
-
requestedPermissions =
|
|
318
|
+
requestedPermissions = RequestedPermissionInternal.FULL_WRITE; // Legacy permission if present is always write
|
|
314
319
|
}
|
|
315
|
-
return yield this.secureDelegationsManager.makeShareOrUpdateRequestParams(entity,
|
|
320
|
+
return yield this.secureDelegationsManager.makeShareOrUpdateRequestParams(entity, currMemberId, Array.from(new Set([...missingSecretIds, ...((_a = userRequestForDelegate === null || userRequestForDelegate === void 0 ? void 0 : userRequestForDelegate.shareSecretIds) !== null && _a !== void 0 ? _a : [])])), Array.from(new Set([...missingEncryptionKeys, ...((_b = userRequestForDelegate === null || userRequestForDelegate === void 0 ? void 0 : userRequestForDelegate.shareEncryptionKeys) !== null && _b !== void 0 ? _b : [])])), Array.from(new Set([...missingOwningEntityIds, ...((_c = userRequestForDelegate === null || userRequestForDelegate === void 0 ? void 0 : userRequestForDelegate.shareOwningEntityIds) !== null && _c !== void 0 ? _c : [])])), requestedPermissions);
|
|
316
321
|
}
|
|
317
322
|
else
|
|
318
323
|
return undefined;
|
|
@@ -320,7 +325,10 @@ class ExtendedApisUtilsImpl {
|
|
|
320
325
|
}
|
|
321
326
|
tryDecryptDataOf(entity, content, validator) {
|
|
322
327
|
return __awaiter(this, void 0, void 0, function* () {
|
|
323
|
-
const
|
|
328
|
+
const dataOwnerIds = this.useParentKeys
|
|
329
|
+
? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()
|
|
330
|
+
: [yield this.dataOwnerApi.getCurrentDataOwnerId()];
|
|
331
|
+
const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds);
|
|
324
332
|
const triedKeys = new Set();
|
|
325
333
|
let latest = yield decryptedKeys.next();
|
|
326
334
|
while (!latest.done) {
|
|
@@ -347,9 +355,10 @@ class ExtendedApisUtilsImpl {
|
|
|
347
355
|
if (!!ensureInitialisedKeysResult) {
|
|
348
356
|
updatedEntity = yield saveEntity(ensureInitialisedKeysResult);
|
|
349
357
|
}
|
|
350
|
-
const
|
|
351
|
-
yield this.dataOwnerApi.
|
|
352
|
-
|
|
358
|
+
const dataOwnerIds = this.useParentKeys
|
|
359
|
+
? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()
|
|
360
|
+
: [yield this.dataOwnerApi.getCurrentDataOwnerId()];
|
|
361
|
+
const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity !== null && updatedEntity !== void 0 ? updatedEntity : entity, type }, dataOwnerIds);
|
|
353
362
|
let latest = yield decryptedKeys.next();
|
|
354
363
|
while (!latest.done) {
|
|
355
364
|
try {
|
|
@@ -506,7 +515,10 @@ class ExtendedApisUtilsImpl {
|
|
|
506
515
|
}
|
|
507
516
|
tryImportFirstValidKey(entity) {
|
|
508
517
|
return __awaiter(this, void 0, void 0, function* () {
|
|
509
|
-
const
|
|
518
|
+
const dataOwnerIds = this.useParentKeys
|
|
519
|
+
? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()
|
|
520
|
+
: [yield this.dataOwnerApi.getCurrentDataOwnerId()];
|
|
521
|
+
const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds);
|
|
510
522
|
let latest = yield generator.next();
|
|
511
523
|
while (!latest.done) {
|
|
512
524
|
const imported = yield this.tryImportKey(latest.value.decrypted);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAuI;AAEvI,gEAAiE;AACjE,2EAAuG;AAEvG,2EAAuE;AAIvE,wFAAoF;AAIpF,sDAA0F;AAC1F,qEAAiE;AAGjE,IAAO,WAAW,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACrD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAC3E,IAAO,2BAA2B,GAAG,uCAAkB,CAAC,2BAA2B,CAAA;AACnF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAGzD;;;GAGG;AACH,MAAa,qBAAqB;IAGhC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,0BAAqE,EACrE,uBAAmE,EACnE,wBAAkD,EAClD,OAAoB,EACpB,aAAsB;QANtB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,+BAA0B,GAA1B,0BAA0B,CAA2C;QACrE,4BAAuB,GAAvB,uBAAuB,CAA4C;QACnE,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,YAAO,GAAP,OAAO,CAAa;QACpB,kBAAa,GAAb,aAAa,CAAS;QAEvC,IAAI,CAAC,4BAA4B,GAAG,IAAI,0DAA8B,CAAC,CAAC,0BAA0B,EAAE,uBA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nimport { b2a, encryptObject, decryptObject, hex2ua, truncateTrailingNulls, ua2utf8, utf8_2ua, EncryptedFieldsManifest } from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { asyncGeneratorToArray } from '../utils/collection-utils'\nimport { SecurityMetadataDecryptor, SecurityMetadataDecryptorChain } from './SecurityMetadataDecryptor'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './LegacyDelegationSecurityMetadataDecryptor'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n private readonly allSecurityMetadataDecryptor: SecurityMetadataDecryptor\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly legacyDelMetadataDecryptor: LegacyDelegationSecurityMetadataDecryptor,\n private readonly secDelMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {\n this.allSecurityMetadataDecryptor = new SecurityMetadataDecryptorChain([legacyDelMetadataDecryptor, secDelMetadataDecryptor])\n }\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.allSecurityMetadataDecryptor.getEntityAccessLevel(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string | undefined }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const newRawKey = initialiseEncryptionKey ? await this.primitives.AES.generateCryptoKey(true) : undefined\n const newSecretId = initialiseSecretId ? this.primitives.randomUuid() : undefined\n return {\n updatedEntity: await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations\n ),\n rawEncryptionKey: newRawKey,\n secretId: newSecretId,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let availableSecretIds: string[] | undefined\n if (unusedSecretIds) {\n availableSecretIds = await this.secretIdsOf(entity)\n }\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n if (!delegateRequests.shareSecretIds && !unusedSecretIds) {\n throw new Error(`Share secret ids parameter is mandatory for entities of type ${entity.type}.`)\n } else if (delegateRequests.shareSecretIds && unusedSecretIds) {\n throw new Error(`Share secret ids parameter must not be unused with entities of type ${entity.type}.`)\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? availableSecretIds!,\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const legacySecretIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy))\n const legacyEncryptionKeys = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy))\n const legacyOwningEntityIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy))\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const legacyAccess =\n selfId === entity.entity.id && dataOwnerId === selfId\n ? AccessLevel.WRITE\n : await this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, [dataOwnerId])\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.includes(dataOwnerId)).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys.filter((x) => x.dataOwnersWithAccess.includes(dataOwnerId)).map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds.filter((x) => x.dataOwnersWithAccess.includes(dataOwnerId)).map((x) => x.decrypted)\n const currentAccess = await this.secDelMetadataDecryptor.getEntityAccessLevel(entity, [dataOwnerId])\n const needsImprovedAccess = legacyAccess === AccessLevel.WRITE && currentAccess !== AccessLevel.WRITE // Only applies to legacy delegations to secure delegations migration: may change if in future we need to migrate from legacy delegations to secure delegations\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [dataOwnerId]))).map((x) => x.decrypted)\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [dataOwnerId]))).map((x) => x.decrypted)\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [dataOwnerId]))).map((x) => x.decrypted)\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n if (needsImprovedAccess || missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0) {\n let requestedPermissions: RequestedPermissionInternal\n if (dataOwnerId === selfId && needsImprovedAccess) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else if (legacyAccess === AccessLevel.WRITE) {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE\n } else {\n requestedPermissions = userRequestForDelegate?.requestedPermissions ?? RequestedPermissionInternal.FULL_READ\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n dataOwnerId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, [await this.dataOwnerApi.getCurrentDataOwnerId()])\n const triedKeys: Set<string> = new Set()\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n if (!triedKeys.has(latest.value.decrypted)) {\n triedKeys.add(latest.value.decrypted)\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(latest.value.decrypted, content)\n if (!validator || (await validator(decrypted))) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n console.warn(`Error while decrypting with raw key ${latest.value}: ${e}`)\n }\n }\n latest = await decryptedKeys.next()\n }\n return { data: content, wasDecrypted: false }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity ?? entity, type }, [\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n ])\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n try {\n return { encryptedData: await this.primitives.AES.encryptWithRawKey(latest.value.decrypted, content), updatedEntity: updatedEntity }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${latest.value}: ${e}`)\n }\n latest = await decryptedKeys.next()\n }\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.decryptAndImportAllDecryptionKeys({ entity: entity, type: entityType })\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity, entityType)\n const updatedEntity = entityWithInitialisedEncryptionKeys ? entityWithInitialisedEncryptionKeys : entity\n const encryptionKey = await this.tryImportFirstValidKey({ entity, type: entityType })\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n updatedEntity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity)) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n entity: EncryptedEntityWithType,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, canDecryptOwnerIds))\n return canDecryptOwnerIds.map((ownerId) => {\n const extracted = this.deduplicate(decryptedData.filter((x) => x.dataOwnersWithAccess.some((o) => o === ownerId)).map((x) => x.decrypted))\n return { ownerId, extracted }\n })\n }\n\n private async decryptAndMergeHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string | undefined,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, hierarchy))\n return this.deduplicate(decryptedData.map((x) => x.decrypted))\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n async decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]> {\n const keys = this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity.entity)\n ? await this.encryptionKeysOf(entity)\n : this.deduplicate(\n await asyncGeneratorToArray(\n this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n ).then((secretIdsInfo) => secretIdsInfo.map(({ decrypted }) => decrypted))\n )\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n async decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(entity)\n if (!res) throw new Error(`Could not find any valid key for entity ${entity.entity.id} (${entity.type}).`)\n return res\n }\n\n private async tryImportFirstValidKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string } | undefined> {\n const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n let latest = await generator.next()\n while (!latest.done) {\n const imported = await this.tryImportKey(latest.value.decrypted)\n if (imported) return { key: imported, raw: latest.value.decrypted }\n latest = await generator.next()\n }\n return undefined\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n argsArray.forEach((arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n } else return false\n }\n return true\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["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CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,IAAI,oBAAoB,EAAE;gBACxB,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;oBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;aACF;;gBAAM,OAAO,KAAK,CAAA;SACpB;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAr0BD,sDAq0BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { b2a, encryptObject, decryptObject, hex2ua, truncateTrailingNulls, ua2utf8, utf8_2ua, EncryptedFieldsManifest } from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { asyncGeneratorToArray } from '../utils/collection-utils'\nimport { SecurityMetadataDecryptor, SecurityMetadataDecryptorChain } from './SecurityMetadataDecryptor'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './LegacyDelegationSecurityMetadataDecryptor'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n private readonly allSecurityMetadataDecryptor: SecurityMetadataDecryptor\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly legacyDelMetadataDecryptor: LegacyDelegationSecurityMetadataDecryptor,\n private readonly secDelMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {\n this.allSecurityMetadataDecryptor = new SecurityMetadataDecryptorChain([legacyDelMetadataDecryptor, secDelMetadataDecryptor])\n }\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.allSecurityMetadataDecryptor.getEntityAccessLevel(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string | undefined }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const newRawKey = initialiseEncryptionKey ? await this.primitives.AES.generateCryptoKey(true) : undefined\n const newSecretId = initialiseSecretId ? this.primitives.randomUuid() : undefined\n return {\n updatedEntity: await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations\n ),\n rawEncryptionKey: newRawKey,\n secretId: newSecretId,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let availableSecretIds: string[] | undefined\n if (unusedSecretIds) {\n availableSecretIds = await this.secretIdsOf(entity)\n }\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n if (!delegateRequests.shareSecretIds && !unusedSecretIds) {\n throw new Error(`Share secret ids parameter is mandatory for entities of type ${entity.type}.`)\n } else if (delegateRequests.shareSecretIds && unusedSecretIds) {\n throw new Error(`Share secret ids parameter must not be unused with entities of type ${entity.type}.`)\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? availableSecretIds!,\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy))\n const legacyEncryptionKeys = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy))\n const legacyOwningEntityIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy))\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id && currMemberId === selfId && !(await this.secDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n const triedKeys: Set<string> = new Set()\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n if (!triedKeys.has(latest.value.decrypted)) {\n triedKeys.add(latest.value.decrypted)\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(latest.value.decrypted, content)\n if (!validator || (await validator(decrypted))) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n console.warn(`Error while decrypting with raw key ${latest.value}: ${e}`)\n }\n }\n latest = await decryptedKeys.next()\n }\n return { data: content, wasDecrypted: false }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity ?? entity, type }, dataOwnerIds)\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n try {\n return { encryptedData: await this.primitives.AES.encryptWithRawKey(latest.value.decrypted, content), updatedEntity: updatedEntity }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${latest.value}: ${e}`)\n }\n latest = await decryptedKeys.next()\n }\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.decryptAndImportAllDecryptionKeys({ entity: entity, type: entityType })\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity, entityType)\n const updatedEntity = entityWithInitialisedEncryptionKeys ? entityWithInitialisedEncryptionKeys : entity\n const encryptionKey = await this.tryImportFirstValidKey({ entity, type: entityType })\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n updatedEntity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity)) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n entity: EncryptedEntityWithType,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, canDecryptOwnerIds))\n return canDecryptOwnerIds.map((ownerId) => {\n const extracted = this.deduplicate(decryptedData.filter((x) => x.dataOwnersWithAccess.some((o) => o === ownerId)).map((x) => x.decrypted))\n return { ownerId, extracted }\n })\n }\n\n private async decryptAndMergeHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string | undefined,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, hierarchy))\n return this.deduplicate(decryptedData.map((x) => x.decrypted))\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n async decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]> {\n const keys = this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity.entity)\n ? await this.encryptionKeysOf(entity)\n : this.deduplicate(\n await asyncGeneratorToArray(\n this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n ).then((secretIdsInfo) => secretIdsInfo.map(({ decrypted }) => decrypted))\n )\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n async decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(entity)\n if (!res) throw new Error(`Could not find any valid key for entity ${entity.entity.id} (${entity.type}).`)\n return res\n }\n\n private async tryImportFirstValidKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string } | undefined> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n let latest = await generator.next()\n while (!latest.done) {\n const imported = await this.tryImportKey(latest.value.decrypted)\n if (imported) return { key: imported, raw: latest.value.decrypted }\n latest = await generator.next()\n }\n return undefined\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n argsArray.forEach((arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n } else return false\n }\n return true\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Participants: A, B children hcp of P ; X external hcp, not related to A/B/P.
|
|
4
|
+
*
|
|
5
|
+
|
|
6
|
+
* Situation 2:
|
|
7
|
+
* Entity E with legacy metadata created by A and shared with P.
|
|
8
|
+
* There is also a confidential secret id (known by A but not P).
|
|
9
|
+
* A wants to share with X as read only.
|
|
10
|
+
* Expected outcome:
|
|
11
|
+
* - A root secure delegation for A
|
|
12
|
+
* - A->A includes the confidential secret id known by A
|
|
13
|
+
* - A delegation from A to P
|
|
14
|
+
* - Through the delegation A->P A and P can access all the legacy metadata available to P (but not the confidential secret id)
|
|
15
|
+
*/
|
|
16
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
17
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
18
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
19
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
20
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
21
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
22
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
const icc_x_api_1 = require("../../../icc-x-api");
|
|
27
|
+
const crypto_1 = require("crypto");
|
|
28
|
+
const test_utils_1 = require("../../utils/test_utils");
|
|
29
|
+
const types_1 = require("@icure/test-setup/types");
|
|
30
|
+
const User_1 = require("../../../icc-api/model/User");
|
|
31
|
+
const TestStorage_1 = require("../../utils/TestStorage");
|
|
32
|
+
const TestCryptoStrategies_1 = require("../../utils/TestCryptoStrategies");
|
|
33
|
+
const icc_api_1 = require("../../../icc-api");
|
|
34
|
+
const chai_1 = require("chai");
|
|
35
|
+
const EntityShareRequest_1 = require("../../../icc-api/model/requests/EntityShareRequest");
|
|
36
|
+
var initMasterApi = test_utils_1.TestUtils.initMasterApi;
|
|
37
|
+
var RequestedPermissionEnum = EntityShareRequest_1.EntityShareRequest.RequestedPermissionEnum;
|
|
38
|
+
(0, test_utils_1.setLocalStorage)(fetch);
|
|
39
|
+
let env;
|
|
40
|
+
describe('Legacy delegations migration test', () => {
|
|
41
|
+
before(function () {
|
|
42
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
43
|
+
this.timeout(600000);
|
|
44
|
+
const initializer = yield (0, test_utils_1.getEnvironmentInitializer)();
|
|
45
|
+
env = yield initializer.execute((0, types_1.getEnvVariables)());
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* Participants:
|
|
50
|
+
*
|
|
51
|
+
* A, B children hcp of P
|
|
52
|
+
* X, X2 are external hcps, not related to A/B/P.
|
|
53
|
+
*/
|
|
54
|
+
// prettier-ignore
|
|
55
|
+
function createTestDataAndApis() {
|
|
56
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
57
|
+
// The following data was created for test purposes only and does not contain any real key / secrets.
|
|
58
|
+
const pId = (0, crypto_1.randomUUID)();
|
|
59
|
+
const pLogin = `parent-${(0, crypto_1.randomUUID)()}`;
|
|
60
|
+
const pPassword = (0, crypto_1.randomUUID)();
|
|
61
|
+
const pPrivateKey = '308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100b8f7e992be3973d42954ca27da89259961c93cca31c6494b074f6f5992ce7ba1d95fdfaf043d5047b6e492c735d68344e0348f08683f1dae728d1e86c439c8498613ec7c8fb54930afbb9f45c74f4d312ecf5d989cb2edd96f887551792094ddd2d18a4c2dc2107c9b044b755f93f8d63e956e1ff0299fa9ed190845f7f5f69dc510df005bd929fb4fed33b30d6e699e0632485cc4180cf5a130357cf64233a680a1a1cc6b6761188192734916cabda14bb954ba3807b84c92f078fe83eea31260390356a8d53853148191144a4584fef02d28bc8353d3c33a87b156396e5fcb7994165da48138db3a3b986fe1c12d46273a218af63b42514690fbb161a5179d0203010001028201000e18c171b03dab58dd5830eff34a7080780b60d952b721eed8927292090b8e308f8dd6fba7a9b9ec929668f94b091b880198ffd84c2eede6d5a41ba779b24da9622687e76bac629f95efb3fbc56cd87289cc13fe058892c7f77ac18b815d1250b58dc7ff20f2f6a95dc7135926a79daca0fdbd1ed756d4c19be8447bd0a200e17419cdd90af54e3b204c1297054d61a6ba9183dfd280d571ee52ee3ed39959abb36ecf575429727d8130bfb070131a46b473a94798834707431bdd248e873d9a716cc469d7f21b545dc2eb21d892e8d94ee6544bd82e8112e697eeaecf6a01d31bffaaf37558aec381f8d12c8491ff77ce00a1da4e2fe6ddf4e5dd14fe1ef90102818100dd2b49e13111593e91a882ae522c1363e2b5e3a10e71c4599e32eec56d9d01682983232b582f2e0923dd107e259771382dd7ff738be31cbba5095153a636dd44e8b08f47e044bbf5814aebdcfed33f0a32fc2f62bf3a0ded9d8aed48fc8034debbf5399862ca2bac72d9d4ab70f90a6a246c6cf4a62c9cb887ea776dce57511902818100d61925b811da57c10e444528230bdb0156516b5ca9ff89a9e57da8373bf5911d009bf5e8a6ee0d40edb89f01e638a528ce592e27d3e7f2172ce373a3b510f2f5045a5dd9aa4ae28b088553a5d099f95611447df464da04168d88ba69751046229131b5a820f9215548de643a82a04ad062ddd74a2e2f30d88480b115c2aa372502818031e374dbce14aabbd9615870f7ea27498db717ac99b481e4f1316df8acbc10b82d3cfe6ee58a66e8fae4ffb664c65f6c9bb2b055a1054ed2e8ec4c23014838eb354db654313b6fe6760eaf5b7f43a961a4948c1fcb20ce497e12fb694e43a12968de6cea79c63ec9bc72746d63a3597d0dd04357803069fd99f302938b4ad8e902818100c167f835ff12b2417924dd2074006ab81b84f3aac2fb501e056d6d3f704fd6e64f3d9478b60bc83746488883cbb8922279be003f0463bcc388ce741188292681868c27c9d0d7532d6be61d7966272221c8f9899af45c2a63413a29c3c8778a1401fbd8f167d00677a79b1709f024e350ba6f52e3f532b63a72005b789fe0ea6d02818100cd0855c641e6294a1c05667f043eedf539c38bbd357dd20dacb182c96455593c689eafc7844d2ba8cd86ce77a3f3151aa261434cdb4d21367c9c62f73289aecb2719de0aca9857365eb16cc56bffbd9b28835eaa4499971996e63306bfdfea35c86179bd749992501aa6c0f45c0123ef6a8a3bb4344c198a0046b94c3bf506f5'; // pragma: allowlist secret
|
|
62
|
+
const pHcpBase = {
|
|
63
|
+
id: pId,
|
|
64
|
+
lastName: '8ed642',
|
|
65
|
+
firstName: 'c9d727',
|
|
66
|
+
publicKey: '30820122300d06092a864886f70d01010105000382010f003082010a0282010100b8f7e992be3973d42954ca27da89259961c93cca31c6494b074f6f5992ce7ba1d95fdfaf043d5047b6e492c735d68344e0348f08683f1dae728d1e86c439c8498613ec7c8fb54930afbb9f45c74f4d312ecf5d989cb2edd96f887551792094ddd2d18a4c2dc2107c9b044b755f93f8d63e956e1ff0299fa9ed190845f7f5f69dc510df005bd929fb4fed33b30d6e699e0632485cc4180cf5a130357cf64233a680a1a1cc6b6761188192734916cabda14bb954ba3807b84c92f078fe83eea31260390356a8d53853148191144a4584fef02d28bc8353d3c33a87b156396e5fcb7994165da48138db3a3b986fe1c12d46273a218af63b42514690fbb161a5179d0203010001', // pragma: allowlist secret
|
|
67
|
+
};
|
|
68
|
+
const pUserBase = {
|
|
69
|
+
id: (0, crypto_1.randomUUID)(),
|
|
70
|
+
name: pLogin,
|
|
71
|
+
status: User_1.User.StatusEnum.ACTIVE,
|
|
72
|
+
login: pLogin,
|
|
73
|
+
passwordHash: pPassword,
|
|
74
|
+
healthcarePartyId: pId,
|
|
75
|
+
email: pLogin,
|
|
76
|
+
};
|
|
77
|
+
const aId = (0, crypto_1.randomUUID)();
|
|
78
|
+
const aLogin = `childA-${(0, crypto_1.randomUUID)()}`;
|
|
79
|
+
const aPassword = (0, crypto_1.randomUUID)();
|
|
80
|
+
const aPrivateKey = '308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100e92f6acc40dbf839fa26e14579fcb68b5e8530f7bfada96338d4f986936cf177e242a458cb1811c2c49c469fa84d2c6ba0c0f34ba6e28babfaff863ff9f3938741d4a41b936143adcff5b396ce12f253e1af424ebd75aa133bdf606b1be51142ee4f5310f4ab46b7a7d706034028f81c462a758f0243d3791d27758bcc8af8010116ee70f1e61eb4526d05d245d631459974eea86b500ad0083e7f196ab9c4926487d92aa2849878f2e4093691d0539b9e880ff6717dbe5e7903141aaf796d74100c42c4d33ac2356df7e3e037accf4495c05f2caf57ae47130b1833f95397e1e9324f2abc1e6af56d7297cf48ea2ba0d990cff2f3b59b1e44efebd4db537ced020301000102820100129e03bed566d42be33a2ea48dcabfd37cc004c13c98e3af3beb8eaee9ebed2d0f2316f667e3d8772b35c3b8eab9cea0e795f356c81d63dd5edacbd325646d7a837367220149e71a97751c73857609ca1cabdea898509508cb49beb88e7c63099ef79bf36302381dfa6e833f2e6496fa8e1df81c04db7971a335d87f7c7660ba6ffb6cc0b3089086df855145b69dba0404ae77b1d533693030e8aa17b851c313d9de7b98a2cd5333fbd1b7d9d7d8d4296c2fc794a50003438eccf0d6dc0a0b34c2695d4f40fa8a5d2de12d5579bc3b33208227cff350413702643f31e0d02317da8165c3f7f1b6a18f00fcea5d981904cb1f5c2bd85d30da963184611f0a06d902818100f6860c1d1c53ad2489bc5e967365e226b25bf292c9ca4f01bbee6d7665f544834f553275e6dc373ed69c942d2e889be2537ae5f5672988c63993bc4f95cbb3dc25b3b8cdf7e274b61532b0e101df22cd54735c2d3f353a4d2d48a1e8dcf11089545b3d8b37f4fa2d3d91129d92e67d9937b065a0bf07c7801df87dd8c1c95f4702818100f2261c810d62345f806345b909e8b1d399d961d5f1bd3c580c96c44ba2e6e532ac93f12cdb25fb6fa9e7a823052c2983611b6c359df98be6c7d0e6377a27cd7f0f67f4568fb72c42d7c3bb13afead3b25a30b7827c1f059d9f75c939fc8608afe2882fdeeb3c292ba45647f373c8ff5719c6da1152c94871b722e8129851a42b028181008fe65945d8d6233833ca27f06c75e957ab3f2ece6e49d06a73b7ce5f914e64eabd313f1e415f044482e3ad3ede6dd188803039f15081971c1659dd4f1b62679fb6c63cb6c5de834012099fe407c2a73ef1efd0bb7cace6564c7b9c3f2050fad51ecf8f92275cb1781cfb04c1c41114f98ddf42c35d1efe5e13a08c5d2d690d5b02818033d7a2fca22fe744970929f13ec4d9e592a7aec18e3ad483895671fa3b8b3180d2dfed9f8bdfaae032410d8749e1359612213bde92cecd7c0045a234386bf31c03e15eb7759762db80b440062c009b8830b50364e54c02f8c71e0191ef9586a099604cd76e07784d06a70e4a79fc8b664b777e527d25e8e3a7b0ca7cc8ad99f70281803b9df4b2e66d849b269300fe42c3136d929fdc184d51283a9fe25772a796ed710b475e85a4e442519a207eeb66e0d89d552798a9b2eb2ebb329109cf4fbce35feba75025a157b57c98776dbe9f04c8937e5cd34021b68ffac95c23c3129967a3aa82ddda35098ba55958e3531fa226825a2685e1ce94353a22a03a1eb9b1a9a0'; // pragma: allowlist secret
|
|
81
|
+
const aHcpBase = {
|
|
82
|
+
id: aId,
|
|
83
|
+
lastName: '6144e2',
|
|
84
|
+
firstName: '6ca3b4',
|
|
85
|
+
parentId: pId,
|
|
86
|
+
aesExchangeKeys: {
|
|
87
|
+
'30820122300d06092a864886f70d01010105000382010f003082010a0282010100e92f6acc40dbf839fa26e14579fcb68b5e8530f7bfada96338d4f986936cf177e242a458cb1811c2c49c469fa84d2c6ba0c0f34ba6e28babfaff863ff9f3938741d4a41b936143adcff5b396ce12f253e1af424ebd75aa133bdf606b1be51142ee4f5310f4ab46b7a7d706034028f81c462a758f0243d3791d27758bcc8af8010116ee70f1e61eb4526d05d245d631459974eea86b500ad0083e7f196ab9c4926487d92aa2849878f2e4093691d0539b9e880ff6717dbe5e7903141aaf796d74100c42c4d33ac2356df7e3e037accf4495c05f2caf57ae47130b1833f95397e1e9324f2abc1e6af56d7297cf48ea2ba0d990cff2f3b59b1e44efebd4db537ced0203010001': // pragma: allowlist secret
|
|
88
|
+
{
|
|
89
|
+
[pId]: {
|
|
90
|
+
'3b42514690fbb161a5179d0203010001': // pragma: allowlist secret
|
|
91
|
+
'4ca457e66519a3f403e089f56f3838a18af16e47029d33ca40eca6a24d1f213809851920b8d159e3879284e5e8d1e0c64be874261d3e0003c43a21ddab9301f8a54161911d3bebe3b1ee6d2a040ec88caa484b6ffd46200bc6eb1a767f309e960f977b9e82d81a0b4961b517e89f24cbc9d0133f955a8d6f792486b1e5dcd9088fe5ecc07b11230b1960013c914041e5de3e9b3c37fa4c2a44dcf2136aae57e000acfe824dacd900bf6be5f6b4f3c41534237a01e14d728065c586dbfd3eeb81ad070218be3e2f70757e9ca5d940afa0b67e02d41e68c1c10935157bc6bd3c06eda95f23c10ca60b649a5ec32903c2a995c0b97fb40cdf454c53621304b0d5b0',
|
|
92
|
+
b59b1e44efebd4db537ced0203010001: '50864963c90cc12704b35ec6cd15ee40a2f4fd4dcb1cf287612346eab4df139008adef1c6d778e35aa7cb58251ff34d6bf1b0faa59d5453c328fa381b175143f41ce66463146b9a02d546cea0065bf62d1ce58e27a8d3bb8bebbb97b76c7e0d7a67b481fdc5082e99aa0521026eb89344b9404da04b0a69988e03724421747e47ab544ed2c55d0424f2837e641f9df4f4ece731e38f9a16d056d9fcf442730c50b3cabcdfbd8241677648639af75198bd30ded0f0fa2db0f8ce80cf86350cef278ce1c7a5426262ceebcc6be5579892d8e066763e216e1592f3f5faa13c561f73400549f5ba2bd618fb308ef99d52cc360ce30988af058caca8c23113933f588', // pragma: allowlist secret
|
|
93
|
+
},
|
|
94
|
+
[aId]: {
|
|
95
|
+
b59b1e44efebd4db537ced0203010001: '189ab5f91d1401fe4c8d2be8e044dcb80211fbf1f310d154a21e32b2b7c0cca715178b42a9a5bbd136b81eed1158da5c8e600e265b38c2b608127b343f0d8da301d80eb24a620ed64bec091771a092a2072a922c2852de55942cc99ae0f9c609150c9621cbaf27740105b28e33668ad0a960c13f884029bb1c8253d646b503ac597f8dbb6ce79b64e7b3929b3a3b649805fb327c2d855f47947e8d5dbf9aa4a0da56b9c1030e9fb1f415d0ee48d91d11c320d1bcba9b96a50574ab406f84629edbb86c68ca548d9dcdd08b4d63c93b3d654e810baaf0782068bc91934fb19f9ab46d940dd3d3e27fc6ac1bcd47440f098d97a9b454df929ba60ae0aa5efe7861', // pragma: allowlist secret
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
publicKey: '30820122300d06092a864886f70d01010105000382010f003082010a0282010100e92f6acc40dbf839fa26e14579fcb68b5e8530f7bfada96338d4f986936cf177e242a458cb1811c2c49c469fa84d2c6ba0c0f34ba6e28babfaff863ff9f3938741d4a41b936143adcff5b396ce12f253e1af424ebd75aa133bdf606b1be51142ee4f5310f4ab46b7a7d706034028f81c462a758f0243d3791d27758bcc8af8010116ee70f1e61eb4526d05d245d631459974eea86b500ad0083e7f196ab9c4926487d92aa2849878f2e4093691d0539b9e880ff6717dbe5e7903141aaf796d74100c42c4d33ac2356df7e3e037accf4495c05f2caf57ae47130b1833f95397e1e9324f2abc1e6af56d7297cf48ea2ba0d990cff2f3b59b1e44efebd4db537ced0203010001', // pragma: allowlist secret
|
|
100
|
+
};
|
|
101
|
+
const aUserBase = {
|
|
102
|
+
id: (0, crypto_1.randomUUID)(),
|
|
103
|
+
name: aLogin,
|
|
104
|
+
status: User_1.User.StatusEnum.ACTIVE,
|
|
105
|
+
login: aLogin,
|
|
106
|
+
passwordHash: aPassword,
|
|
107
|
+
healthcarePartyId: aId,
|
|
108
|
+
autoDelegations: {
|
|
109
|
+
all: [pId],
|
|
110
|
+
},
|
|
111
|
+
email: aLogin,
|
|
112
|
+
};
|
|
113
|
+
const bId = (0, crypto_1.randomUUID)();
|
|
114
|
+
const bLogin = `childB-${(0, crypto_1.randomUUID)()}`;
|
|
115
|
+
const bPassword = (0, crypto_1.randomUUID)();
|
|
116
|
+
const bPrivateKey = '308204bc020100300d06092a864886f70d0101010500048204a6308204a20201000282010100982330dc464b3e9c583affbfece209976bc045f07b22fb44bcb0ebc27bc9d8406b54e380d195e107c1728499a64012b3251c1c85a2516e73b89a07b1929f0c12d44828677135082e8170b9831dd4ff9e988d098731eadd1443813cb5f6af2fe4c2a2706ba6aeb5bb6bb7889be51eebd83bebbb2a0b55a6d69fdeb66894af47edd6f82a8d30629814b82f17cfd1ef75f47d192eb9577c58f14a5e0d2782b13b796b5a3be780a38b0f69f3d00179d13cc23fcec1e919ac05d88c08c693c711384ad9fc7a21ed28d0e5d3865c15db239a5d727d4c52a344975c97379cc5a195ff4f8c1aacbaa67d6d0fd358b6b5d1a4d0575bc57b2d7736108978e3371e9aa0ae8f0203010001028201002a9bac7afc9ae5399f4242cf4b36110e9de8570e1f46704dd374cf4a8425c7115f9e022b59475b23336bf1b4208a1052a8e183217010d358c88a26fe75fc6242c1be45c696bf8dff8c53f838bef9a0ef9774e486bf15b27e12dbd69775b3a1bbb5410e303019fd1eb4efcd6c2fd2a5a5c53e6388466d6210f8ec4474ecb35c76d2c4269d3a585cdce972673c56818015b9f097ff528e26272b76810cb4f8a1ee5ea04ea26f4cf3c6f78b77c5f58d80628f513a4da76cc1e35a6867af1ab76fe0354e549340221d19bfe04783e34f84eca7bd80867134710adc0665a52eb689d2cf6ecb38ca77d84f4feb8c23539e92ac870b3175c174d8f5643aabc0e7ef3cd102818100ba44b38b24e28d9fb85279c0098b4505e0852ba88b54d2cb8b0e77368c1600bb40b4c0f6dee8b97788e082af0f9045dd54f05ee583fffabc473d16272d03c1aef301541176e7a95f948f8d77b6aad087c54f2de713909efdd5d90a8bbec61067172a97480ba844c25cf64a8b1f0698e2f4dd73af798dd8ab329f7f9bf9a0f9ff02818100d11781567bde00a256ac7ef2c4bf10a5b8b2ebab77c941b7665817f17aa496f166ecd89bb4c50c53d4e836b3369edc2f0f49e64f8dbe7ddaf0fb3898075f6e82ab2c69bc925368904ba459ce08a40ce621dceefa78b64d8eb68752d1cc2a53a1db9718ab1a8703333065cf9b8407174c18f8b085e4aebf32a5bf9b259a6bab71028180492352b04f025a039df75c70e80e7442b37ef6be8e3ef72a0ee6d62e67e0f7d68eb8aa9004c4b29659fb75b4d1529fec213ee4b4101981d54dcf91943e5b9c405a9069f7158e2ef625ba1c1d266f79c3e5d88a38927915c4aba4363cdae2a06c2a2f82093af28e5516f56a1da84809de0bb1ac8bf919963ada7cc039795218f70281802b0aceaa31f78263e8b9bbac580a08f04474388564b43e5df5a87ecd4bf4e3c9afe963b1b1e5ba62eb7a1e008866ed66969c1cd81592b82fc0d9c64dad7edcadf374c2137a7fc70fa532a0f603db59786a5223b3d5f399459e977eda0750534507823426cce02c2d76720ee9b1a5100baf3c4a8255900f75ea9ee5de38ca9f510281802c19faaa1e08ac6337c48af1529f8b8685d2582586986b180377aee8cf4eaadcdbb5869c6f994275b0ae3ecc6aa0ead81296ab9a96eecb44f14fcd9e50ef34d9725e97809b3ed2ed6105102c96ea55a096f292a8d9769c05779f303dc6ad3b30c3c9bea749d58636b3977c9c593557c048b2f82e90fead32b5b510966e548e7a'; // pragma: allowlist secret
|
|
117
|
+
const bHcpBase = {
|
|
118
|
+
id: bId,
|
|
119
|
+
lastName: '95ee22',
|
|
120
|
+
firstName: '2af696',
|
|
121
|
+
parentId: pId,
|
|
122
|
+
aesExchangeKeys: {
|
|
123
|
+
'30820122300d06092a864886f70d01010105000382010f003082010a0282010100982330dc464b3e9c583affbfece209976bc045f07b22fb44bcb0ebc27bc9d8406b54e380d195e107c1728499a64012b3251c1c85a2516e73b89a07b1929f0c12d44828677135082e8170b9831dd4ff9e988d098731eadd1443813cb5f6af2fe4c2a2706ba6aeb5bb6bb7889be51eebd83bebbb2a0b55a6d69fdeb66894af47edd6f82a8d30629814b82f17cfd1ef75f47d192eb9577c58f14a5e0d2782b13b796b5a3be780a38b0f69f3d00179d13cc23fcec1e919ac05d88c08c693c711384ad9fc7a21ed28d0e5d3865c15db239a5d727d4c52a344975c97379cc5a195ff4f8c1aacbaa67d6d0fd358b6b5d1a4d0575bc57b2d7736108978e3371e9aa0ae8f0203010001': // pragma: allowlist secret
|
|
124
|
+
{
|
|
125
|
+
[pId]: {
|
|
126
|
+
'3b42514690fbb161a5179d0203010001': // pragma: allowlist secret
|
|
127
|
+
'5e186cec6d6ddb277aa5421a345045f5f44aa125844e833529fccfeb3a002dd4aef78d84b5b8710ff0aa375436e2abdea07a2cb186cd914fa8b8fb86ab1201b109d802927b49517322ac6521600a123ee03d9383154b6f0fa0e99a8ca6e73e07ceed4aeb835649a850316c5585b2a69ac6703c7154f2db981913bac36a0cea515c70c505d1dc3a7e3a6db519cf7b68737a80ad102cc575959b08fbe327644e7d1b7da0737bfa6ededdd7bf0538fd3dc040ac57937bebdf3146a566c2619314935bc610e900b9c350fcf21a9b20c47f0ee25112578dc210b6b17c4cad9687d2bd9abab12f03f8b778b74186ac3c61d57058037d0e00903c74d2eaa8b2fdb90e3f',
|
|
128
|
+
'36108978e3371e9aa0ae8f0203010001': // pragma: allowlist secret
|
|
129
|
+
'89764feb4d23d8313d58c0568088ecf9f320dd285eb762eaee8593a9ecc884a54e4eb6cd93a87f1383f345b94b8a7f1d20dda33d972ab4460aef742d44837648403234700a5a9f85032b025c533aebdc7bea07dec17c7a1737a51f873ec36c689a29b3314fa2d0f77d7e83e71e5a1de1392a6e92fb9881d811253f2bc00db0798e213899a85bcf0bafeaf8b972c40b1a0d1dd3109e6a8bc9309caa5ada9bc41ea62c72fbdf7cf49cbbe15cd048e6d614a4d65e09f5bed014975ea19c160e3754abd9031e8a41283fa369fa621685aee16c5a5d18a1811fde27869cb156a00fe28ae42c9ff498f2c3dd88a392ac9d68d9885556effe62850681fa8fbe5e02781f', // pragma: allowlist secret
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
publicKey: '30820122300d06092a864886f70d01010105000382010f003082010a0282010100982330dc464b3e9c583affbfece209976bc045f07b22fb44bcb0ebc27bc9d8406b54e380d195e107c1728499a64012b3251c1c85a2516e73b89a07b1929f0c12d44828677135082e8170b9831dd4ff9e988d098731eadd1443813cb5f6af2fe4c2a2706ba6aeb5bb6bb7889be51eebd83bebbb2a0b55a6d69fdeb66894af47edd6f82a8d30629814b82f17cfd1ef75f47d192eb9577c58f14a5e0d2782b13b796b5a3be780a38b0f69f3d00179d13cc23fcec1e919ac05d88c08c693c711384ad9fc7a21ed28d0e5d3865c15db239a5d727d4c52a344975c97379cc5a195ff4f8c1aacbaa67d6d0fd358b6b5d1a4d0575bc57b2d7736108978e3371e9aa0ae8f0203010001', // pragma: allowlist secret
|
|
134
|
+
};
|
|
135
|
+
const bUserBase = {
|
|
136
|
+
id: (0, crypto_1.randomUUID)(),
|
|
137
|
+
name: bLogin,
|
|
138
|
+
status: User_1.User.StatusEnum.ACTIVE,
|
|
139
|
+
login: bLogin,
|
|
140
|
+
passwordHash: bPassword,
|
|
141
|
+
groupId: 'test-group',
|
|
142
|
+
healthcarePartyId: bId,
|
|
143
|
+
autoDelegations: {
|
|
144
|
+
all: [pId],
|
|
145
|
+
},
|
|
146
|
+
email: bLogin,
|
|
147
|
+
};
|
|
148
|
+
const patientConfidentialSecretId = '24cd8cf5-0958-4ee9-8e90-95f3d25a47d7';
|
|
149
|
+
const patientBase = {
|
|
150
|
+
id: (0, crypto_1.randomUUID)(),
|
|
151
|
+
firstName: 'John',
|
|
152
|
+
lastName: 'Doe',
|
|
153
|
+
delegations: {
|
|
154
|
+
[aId]: [
|
|
155
|
+
{
|
|
156
|
+
owner: aId,
|
|
157
|
+
delegatedTo: aId,
|
|
158
|
+
key: '4bd1316d494e858496f1d6c1200726cb76c7ff98fb47eddb1c0bf5b79712230db3f02bdf60599816e0601628ee349674a0509720e9972d87b2370b60bcbbb19adb2980bc1ab5bab8b9c8adc5516d39d0cf2d6c373fe7285ce0f1018058e52fcc',
|
|
159
|
+
tags: ['confidential'],
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
owner: aId,
|
|
163
|
+
delegatedTo: aId,
|
|
164
|
+
key: '6121912dea437ddaf92c41a43deba576976a2b7c10c1cbba79624634ded8bb5d0210db5e339e3e26d33e6e2d18d6b8acc91f8415e5ab488b9227f7c6f6f370873f1d5b5ff3afd28dfe6e47ed10b0cb435676a4db039469a50547f3e1e515fc63', // pragma: allowlist secret
|
|
165
|
+
},
|
|
166
|
+
],
|
|
167
|
+
[pId]: [
|
|
168
|
+
{
|
|
169
|
+
owner: aId,
|
|
170
|
+
delegatedTo: pId,
|
|
171
|
+
key: '0b293a861d76b21928c6689fb80c373f16bfbe8269ef201b5af35ff4634e51af1c5d3c535c384efea3126acee3572b815db950c52298b1ee99868041641110100c51ad3bc6d0bafddd5021b50b8e0fd16c44f5fd05617eae4f5a00c090c0ccfb', // pragma: allowlist secret
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
},
|
|
175
|
+
encryptionKeys: {
|
|
176
|
+
[aId]: [
|
|
177
|
+
{
|
|
178
|
+
owner: aId,
|
|
179
|
+
delegatedTo: aId,
|
|
180
|
+
key: '42e625cb8930ca763f6b604d08775b4231e9414fa953feeafbd7cfc6acc138bdbf5013aa211935f9f429a627db5d41efa617b2ae9d46f93d83db73b36dab7892c07b03408ee4ab50974b0d4081162b4e9a2a448ce00e35d05aac4d7e675e99b3', // pragma: allowlist secret
|
|
181
|
+
},
|
|
182
|
+
],
|
|
183
|
+
[pId]: [
|
|
184
|
+
{
|
|
185
|
+
owner: aId,
|
|
186
|
+
delegatedTo: pId,
|
|
187
|
+
key: '194ee902b4780178fd88ffddd1e0744537ddf952d306dfe1123b14bec4405dc1f6b9aea7444cc74f5acca0d18062c0e12d7d9bb6c7b7bff27efb681c7e5ca52f25797f45207f63c13778637a40a541a2e33d79dc1660d7f898d69c92a93aedcf', // pragma: allowlist secret
|
|
188
|
+
},
|
|
189
|
+
],
|
|
190
|
+
},
|
|
191
|
+
encryptedSelf: 'jgAFAlmd2QStXpOt3LnIhs4upJv2e10fp0u6/PburW7mq1r3vo/Q5/a4Yk7EWXG7oydMWb2i1UCCiNN80czGdA==', // pragma: allowlist secret
|
|
192
|
+
};
|
|
193
|
+
const testSetupApi = yield initMasterApi(env);
|
|
194
|
+
yield testSetupApi.healthcarePartyApi.createHealthcareParty(pHcpBase);
|
|
195
|
+
const pUser = yield testSetupApi.userApi.createUser(pUserBase);
|
|
196
|
+
yield testSetupApi.healthcarePartyApi.createHealthcareParty(aHcpBase);
|
|
197
|
+
const aUser = yield testSetupApi.userApi.createUser(aUserBase);
|
|
198
|
+
yield testSetupApi.healthcarePartyApi.createHealthcareParty(bHcpBase);
|
|
199
|
+
const bUser = yield testSetupApi.userApi.createUser(bUserBase);
|
|
200
|
+
const pStorage = yield (0, TestStorage_1.testStorageWithKeys)([
|
|
201
|
+
{
|
|
202
|
+
dataOwnerId: pHcpBase.id,
|
|
203
|
+
pairs: [{ keyPair: { privateKey: pPrivateKey, publicKey: pHcpBase.publicKey }, shaVersion: icc_x_api_1.ShaVersion.Sha1 }],
|
|
204
|
+
},
|
|
205
|
+
]);
|
|
206
|
+
const aStorage = yield (0, TestStorage_1.testStorageWithKeys)([
|
|
207
|
+
{
|
|
208
|
+
dataOwnerId: aHcpBase.id,
|
|
209
|
+
pairs: [{ keyPair: { privateKey: aPrivateKey, publicKey: aHcpBase.publicKey }, shaVersion: icc_x_api_1.ShaVersion.Sha1 }],
|
|
210
|
+
},
|
|
211
|
+
{
|
|
212
|
+
dataOwnerId: pHcpBase.id,
|
|
213
|
+
pairs: [{ keyPair: { privateKey: pPrivateKey, publicKey: pHcpBase.publicKey }, shaVersion: icc_x_api_1.ShaVersion.Sha1 }],
|
|
214
|
+
},
|
|
215
|
+
]);
|
|
216
|
+
const bStorage = yield (0, TestStorage_1.testStorageWithKeys)([
|
|
217
|
+
{
|
|
218
|
+
dataOwnerId: bHcpBase.id,
|
|
219
|
+
pairs: [{ keyPair: { privateKey: bPrivateKey, publicKey: bHcpBase.publicKey }, shaVersion: icc_x_api_1.ShaVersion.Sha1 }],
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
dataOwnerId: pHcpBase.id,
|
|
223
|
+
pairs: [{ keyPair: { privateKey: pPrivateKey, publicKey: pHcpBase.publicKey }, shaVersion: icc_x_api_1.ShaVersion.Sha1 }],
|
|
224
|
+
},
|
|
225
|
+
]);
|
|
226
|
+
const pApi = yield icc_x_api_1.IcureApi.initialise(env.iCureUrl, { username: pLogin, password: pPassword }, new TestCryptoStrategies_1.TestCryptoStrategies(), crypto_1.webcrypto, fetch, {
|
|
227
|
+
storage: pStorage.storage,
|
|
228
|
+
keyStorage: pStorage.keyStorage,
|
|
229
|
+
entryKeysFactory: pStorage.keyFactory,
|
|
230
|
+
disableParentKeysInitialisation: false,
|
|
231
|
+
});
|
|
232
|
+
const aApi = yield icc_x_api_1.IcureApi.initialise(env.iCureUrl, { username: aLogin, password: aPassword }, new TestCryptoStrategies_1.TestCryptoStrategies(), crypto_1.webcrypto, fetch, {
|
|
233
|
+
storage: aStorage.storage,
|
|
234
|
+
keyStorage: aStorage.keyStorage,
|
|
235
|
+
entryKeysFactory: aStorage.keyFactory,
|
|
236
|
+
disableParentKeysInitialisation: false,
|
|
237
|
+
});
|
|
238
|
+
const bApi = yield icc_x_api_1.IcureApi.initialise(env.iCureUrl, { username: bLogin, password: bPassword }, new TestCryptoStrategies_1.TestCryptoStrategies(), crypto_1.webcrypto, fetch, {
|
|
239
|
+
storage: bStorage.storage,
|
|
240
|
+
keyStorage: bStorage.keyStorage,
|
|
241
|
+
entryKeysFactory: bStorage.keyFactory,
|
|
242
|
+
disableParentKeysInitialisation: false,
|
|
243
|
+
});
|
|
244
|
+
const xInfo = yield (0, test_utils_1.createNewHcpApi)(env);
|
|
245
|
+
const x2Info = yield (0, test_utils_1.createNewHcpApi)(env);
|
|
246
|
+
const apis = { a: aApi, b: bApi, p: pApi, x: xInfo.api, x2: x2Info.api };
|
|
247
|
+
const xUser = xInfo.user;
|
|
248
|
+
const xCredentials = xInfo.credentials;
|
|
249
|
+
const x2User = x2Info.user;
|
|
250
|
+
const x2Credentials = x2Info.credentials;
|
|
251
|
+
const patient = yield new icc_api_1.IccPatientApi(env.iCureUrl, {}, aApi.authApi.authenticationProvider, fetch).createPatient(patientBase);
|
|
252
|
+
const ids = {
|
|
253
|
+
a: aId,
|
|
254
|
+
b: bId,
|
|
255
|
+
p: pId,
|
|
256
|
+
x: xCredentials.dataOwnerId,
|
|
257
|
+
x2: x2Credentials.dataOwnerId,
|
|
258
|
+
};
|
|
259
|
+
console.log(JSON.stringify(ids, undefined, 2));
|
|
260
|
+
return {
|
|
261
|
+
apis,
|
|
262
|
+
ids,
|
|
263
|
+
users: {
|
|
264
|
+
a: aUser,
|
|
265
|
+
b: bUser,
|
|
266
|
+
p: pUser,
|
|
267
|
+
x: xUser,
|
|
268
|
+
x2: x2User,
|
|
269
|
+
},
|
|
270
|
+
patient,
|
|
271
|
+
patientConfidentialSecretId,
|
|
272
|
+
patientNote: 'This is just a test patient',
|
|
273
|
+
};
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
/*
|
|
277
|
+
* Entity E with legacy metadata created by A and shared with P.
|
|
278
|
+
* There is also a confidential secret id (known by A but not P).
|
|
279
|
+
* B wants to share with X as read only.
|
|
280
|
+
* Expected outcome:
|
|
281
|
+
* - A root secure delegation B->B
|
|
282
|
+
* - A delegation B->P
|
|
283
|
+
* - Through the delegation B->P A and P can access all the legacy metadata available to P (but not the confidential secret id known by A)
|
|
284
|
+
* - A delegation from B->X
|
|
285
|
+
* - Through B->X X can access only the shared information and has read access only
|
|
286
|
+
*
|
|
287
|
+
* Now A wants to share with X2.
|
|
288
|
+
* Expected outcome:
|
|
289
|
+
* - A new root secure delegation A->A is available, which gives access to the confidential secret id
|
|
290
|
+
* - A delegation A->X2 with the shared information.
|
|
291
|
+
* - Parents of the new delegation are the new A->A root delegation and the existing A->P delegation.
|
|
292
|
+
* - B and P still can't access the confidential secret id.
|
|
293
|
+
*/
|
|
294
|
+
it('sharing data as a child of a parent with legacy access should work', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
295
|
+
var _a, _b, _c, _d;
|
|
296
|
+
console.log('Creating test data');
|
|
297
|
+
const { apis, ids, patient, patientConfidentialSecretId, users, patientNote } = yield createTestDataAndApis();
|
|
298
|
+
console.log('Starting test');
|
|
299
|
+
const secretIdsKnownByA = new Set(yield apis.a.patientApi.decryptSecretIdsOf(patient));
|
|
300
|
+
const secretIdsKnownByB = new Set(yield apis.b.patientApi.decryptSecretIdsOf(patient));
|
|
301
|
+
(0, chai_1.expect)(secretIdsKnownByB.size).to.eq(1);
|
|
302
|
+
(0, chai_1.expect)(secretIdsKnownByB.has(patientConfidentialSecretId)).to.be.false;
|
|
303
|
+
(0, chai_1.expect)(secretIdsKnownByA.size).to.eq(2);
|
|
304
|
+
(0, chai_1.expect)(secretIdsKnownByA.has(patientConfidentialSecretId)).to.be.true;
|
|
305
|
+
(0, chai_1.expect)(secretIdsKnownByA.has([...secretIdsKnownByB][0])).to.be.true;
|
|
306
|
+
const sharedPatient = yield apis.b.patientApi.shareWith(ids.x, patient, [...secretIdsKnownByB], {
|
|
307
|
+
requestedPermissions: RequestedPermissionEnum.FULL_READ,
|
|
308
|
+
});
|
|
309
|
+
const secureDelegations = Object.values((_b = (_a = sharedPatient.securityMetadata) === null || _a === void 0 ? void 0 : _a.secureDelegations) !== null && _b !== void 0 ? _b : {});
|
|
310
|
+
(0, chai_1.expect)(secureDelegations).to.have.length(3);
|
|
311
|
+
(0, chai_1.expect)(secureDelegations.find((d) => d.delegator === ids.b && d.delegate === ids.b)).to.not.be.undefined;
|
|
312
|
+
(0, chai_1.expect)(secureDelegations.find((d) => d.delegator === ids.b && d.delegate === ids.p)).to.not.be.undefined;
|
|
313
|
+
const sharedPatientWithoutLegacyDetails = Object.assign(Object.assign({}, sharedPatient), { delegations: {}, encryptionKeys: {} });
|
|
314
|
+
(0, chai_1.expect)(yield apis.a.patientApi.getEncryptionKeysOf(sharedPatientWithoutLegacyDetails)).to.have.length(1);
|
|
315
|
+
(0, chai_1.expect)(yield apis.a.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails)).to.have.members([...secretIdsKnownByB]);
|
|
316
|
+
(0, chai_1.expect)(secureDelegations.find((d) => d.delegator === ids.b && d.delegate === ids.x)).to.not.be.undefined;
|
|
317
|
+
(0, chai_1.expect)((yield apis.x.patientApi.getPatientWithUser(users.x, patient.id)).note).to.eq(patientNote);
|
|
318
|
+
(0, chai_1.expect)(yield apis.x.cryptoApi.xapi.hasWriteAccess({ entity: sharedPatient, type: icc_x_api_1.EntityWithDelegationTypeName.Patient })).to.be.false;
|
|
319
|
+
(0, chai_1.expect)(yield apis.x.patientApi.modifyPatientWithUser(users.x, Object.assign(Object.assign({}, sharedPatient), { firstName: 'New name' })).then(() => true, () => false)).to.be.false;
|
|
320
|
+
(0, chai_1.expect)(yield apis.x.patientApi.decryptSecretIdsOf(sharedPatient)).to.have.members([...secretIdsKnownByB]);
|
|
321
|
+
const sharedPatient2 = yield apis.a.patientApi.shareWith(ids.x2, sharedPatient, [...secretIdsKnownByB], {
|
|
322
|
+
requestedPermissions: RequestedPermissionEnum.FULL_READ,
|
|
323
|
+
});
|
|
324
|
+
const secureDelegations2 = Object.values((_d = (_c = sharedPatient2.securityMetadata) === null || _c === void 0 ? void 0 : _c.secureDelegations) !== null && _d !== void 0 ? _d : {});
|
|
325
|
+
(0, chai_1.expect)(secureDelegations2).to.have.length(5);
|
|
326
|
+
(0, chai_1.expect)(secureDelegations2.find((d) => d.delegator === ids.a && d.delegate === ids.a)).to.not.be.undefined;
|
|
327
|
+
const secureDelegationAtoX2 = secureDelegations2.find((d) => d.delegator === ids.a && d.delegate === ids.x2);
|
|
328
|
+
(0, chai_1.expect)(secureDelegationAtoX2).to.not.be.undefined;
|
|
329
|
+
(0, chai_1.expect)(secureDelegationAtoX2 === null || secureDelegationAtoX2 === void 0 ? void 0 : secureDelegationAtoX2.parentDelegations).to.have.length(2);
|
|
330
|
+
(0, chai_1.expect)(yield apis.b.patientApi.decryptSecretIdsOf(sharedPatient2)).to.have.members([...secretIdsKnownByB]);
|
|
331
|
+
}));
|
|
332
|
+
/*
|
|
333
|
+
* Entity E with legacy metadata created by A and shared with P.
|
|
334
|
+
* There is also a confidential secret id (known by A but not P).
|
|
335
|
+
* A wants to share with X as read only.
|
|
336
|
+
* Expected outcome:
|
|
337
|
+
* - A root secure delegation for A
|
|
338
|
+
* - A->A includes the confidential secret id known by A
|
|
339
|
+
* - A delegation from A to P
|
|
340
|
+
* - Through the delegation A->P A and P can access all the legacy metadata available to P (but not the confidential secret id)
|
|
341
|
+
*/
|
|
342
|
+
it('sharing data created with legacy api by the same user ', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
343
|
+
var _e, _f;
|
|
344
|
+
console.log('Creating test data');
|
|
345
|
+
const { apis, ids, patient, patientConfidentialSecretId, users, patientNote } = yield createTestDataAndApis();
|
|
346
|
+
console.log('Starting test');
|
|
347
|
+
const secretIdsKnownByA = new Set(yield apis.a.patientApi.decryptSecretIdsOf(patient));
|
|
348
|
+
const secretIdsKnownByB = new Set(yield apis.b.patientApi.decryptSecretIdsOf(patient));
|
|
349
|
+
const sharedPatient = yield apis.a.patientApi.shareWith(ids.x, patient, [...secretIdsKnownByB], {
|
|
350
|
+
requestedPermissions: RequestedPermissionEnum.FULL_READ,
|
|
351
|
+
});
|
|
352
|
+
const secureDelegations = Object.values((_f = (_e = sharedPatient.securityMetadata) === null || _e === void 0 ? void 0 : _e.secureDelegations) !== null && _f !== void 0 ? _f : {});
|
|
353
|
+
(0, chai_1.expect)(secureDelegations).to.have.length(3);
|
|
354
|
+
(0, chai_1.expect)(secureDelegations.find((d) => d.delegator === ids.a && d.delegate === ids.a)).to.not.be.undefined;
|
|
355
|
+
(0, chai_1.expect)(secureDelegations.find((d) => d.delegator === ids.a && d.delegate === ids.p)).to.not.be.undefined;
|
|
356
|
+
(0, chai_1.expect)(secureDelegations.find((d) => d.delegator === ids.a && d.delegate === ids.x)).to.not.be.undefined;
|
|
357
|
+
const sharedPatientWithoutLegacyDetails = Object.assign(Object.assign({}, sharedPatient), { delegations: {}, encryptionKeys: {} });
|
|
358
|
+
console.log(yield apis.a.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails));
|
|
359
|
+
console.log(yield apis.b.patientApi.decryptSecretIdsOf(sharedPatient));
|
|
360
|
+
console.log(yield apis.b.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails));
|
|
361
|
+
console.log(yield apis.x.patientApi.decryptSecretIdsOf(sharedPatient));
|
|
362
|
+
(0, chai_1.expect)(yield apis.a.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails)).to.have.members([...secretIdsKnownByA]);
|
|
363
|
+
(0, chai_1.expect)(yield apis.b.patientApi.decryptSecretIdsOf(sharedPatient)).to.have.members([...secretIdsKnownByB]);
|
|
364
|
+
(0, chai_1.expect)(yield apis.b.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails)).to.have.members([...secretIdsKnownByB]);
|
|
365
|
+
(0, chai_1.expect)(yield apis.x.patientApi.decryptSecretIdsOf(sharedPatient)).to.have.members([...secretIdsKnownByB]);
|
|
366
|
+
console.log(JSON.stringify(sharedPatient, undefined, 2));
|
|
367
|
+
}));
|
|
368
|
+
});
|
|
369
|
+
//# sourceMappingURL=legacy-metadata-migration-test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"legacy-metadata-migration-test.js","sourceRoot":"","sources":["../../../../test/icc-x-api/crypto/legacy-metadata-migration-test.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;;;;;;;;;AAEH,kDAAuF;AACvF,mCAA8C;AAC9C,uDAA+G;AAC/G,mDAAmE;AACnE,sDAAkD;AAGlD,yDAA6D;AAC7D,2EAAuE;AACvE,8CAAgD;AAChD,+BAA6B;AAC7B,2FAAuF;AACvF,IAAO,aAAa,GAAG,sBAAS,CAAC,aAAa,CAAA;AAC9C,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAG3E,IAAA,4BAAe,EAAC,KAAK,CAAC,CAAA;AAEtB,IAAI,GAAa,CAAA;AAEjB,QAAQ,CAAC,mCAAmC,EAAE,GAAG,EAAE;IACjD,MAAM,CAAC;;YACL,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;YACpB,MAAM,WAAW,GAAG,MAAM,IAAA,sCAAyB,GAAE,CAAA;YACrD,GAAG,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,IAAA,uBAAe,GAAE,CAAC,CAAA;QACpD,CAAC;KAAA,CAAC,CAAA;IAEF;;;;;OAKG;IACH,kBAAkB;IAClB,SAAe,qBAAqB;;YAQlC,qGAAqG;YACrG,MAAM,GAAG,GAAG,IAAA,mBAAU,GAAE,CAAA;YACxB,MAAM,MAAM,GAAG,UAAU,IAAA,mBAAU,GAAE,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AO,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAA;QAC7H,IAAA,aAAM,EAAC,MAAM,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAA;QACzG,IAAA,aAAM,EAAC,MAAM,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,kBAAkB,CAAC,iCAAiC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAA;QAC7H,IAAA,aAAM,EAAC,MAAM,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAA;QACzG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,aAAa,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAA;IAC1D,CAAC,CAAA,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA","sourcesContent":["/*\n * Participants: A, B children hcp of P ; X external hcp, not related to A/B/P.\n *\n\n * Situation 2:\n * Entity E with legacy metadata created by A and shared with P.\n * There is also a confidential secret id (known by A but not P).\n * A wants to share with X as read only.\n * Expected outcome:\n * - A root secure delegation for A\n * - A->A includes the confidential secret id known by A\n * - A delegation from A to P\n * - Through the delegation A->P A and P can access all the legacy metadata available to P (but not the confidential secret id)\n */\n\nimport { EntityWithDelegationTypeName, IcureApi, ShaVersion } from '../../../icc-x-api'\nimport { randomUUID, webcrypto } from 'crypto'\nimport { createNewHcpApi, getEnvironmentInitializer, setLocalStorage, TestUtils } from '../../utils/test_utils'\nimport { getEnvVariables, TestVars } from '@icure/test-setup/types'\nimport { User } from '../../../icc-api/model/User'\nimport { HealthcareParty } from '../../../icc-api/model/HealthcareParty'\nimport { Patient } from '../../../icc-api/model/Patient'\nimport { testStorageWithKeys } from '../../utils/TestStorage'\nimport { TestCryptoStrategies } from '../../utils/TestCryptoStrategies'\nimport { IccPatientApi } from '../../../icc-api'\nimport { expect } from 'chai'\nimport { EntityShareRequest } from '../../../icc-api/model/requests/EntityShareRequest'\nimport initMasterApi = TestUtils.initMasterApi\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { SecureDelegationsSecurityMetadataDecryptor } from '../../../icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor'\n\nsetLocalStorage(fetch)\n\nlet env: TestVars\n\ndescribe('Legacy delegations migration test', () => {\n before(async function () {\n this.timeout(600000)\n const initializer = await getEnvironmentInitializer()\n env = await initializer.execute(getEnvVariables())\n })\n\n /**\n * Participants:\n *\n * A, B children hcp of P\n * X, X2 are external hcps, not related to A/B/P.\n */\n // prettier-ignore\n async function createTestDataAndApis(): Promise<{\n patientConfidentialSecretId: string\n apis: { a: IcureApi; b: IcureApi; p: IcureApi; x: IcureApi; x2: IcureApi }\n users: { a: User; b: User; p: User; x: User; x2: User }\n patient: Patient\n patientNote: string\n ids: { p: string; a: string; b: string; x: string; x2: string }\n }> {\n // The following data was created for test purposes only and does not contain any real key / secrets.\n const pId = randomUUID()\n const pLogin = `parent-${randomUUID()}`\n const pPassword = randomUUID()\n const pPrivateKey =\n '308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100b8f7e992be3973d42954ca27da89259961c93cca31c6494b074f6f5992ce7ba1d95fdfaf043d5047b6e492c735d68344e0348f08683f1dae728d1e86c439c8498613ec7c8fb54930afbb9f45c74f4d312ecf5d989cb2edd96f887551792094ddd2d18a4c2dc2107c9b044b755f93f8d63e956e1ff0299fa9ed190845f7f5f69dc510df005bd929fb4fed33b30d6e699e0632485cc4180cf5a130357cf64233a680a1a1cc6b6761188192734916cabda14bb954ba3807b84c92f078fe83eea31260390356a8d53853148191144a4584fef02d28bc8353d3c33a87b156396e5fcb7994165da48138db3a3b986fe1c12d46273a218af63b42514690fbb161a5179d0203010001028201000e18c171b03dab58dd5830eff34a7080780b60d952b721eed8927292090b8e308f8dd6fba7a9b9ec929668f94b091b880198ffd84c2eede6d5a41ba779b24da9622687e76bac629f95efb3fbc56cd87289cc13fe058892c7f77ac18b815d1250b58dc7ff20f2f6a95dc7135926a79daca0fdbd1ed756d4c19be8447bd0a200e17419cdd90af54e3b204c1297054d61a6ba9183dfd280d571ee52ee3ed39959abb36ecf575429727d8130bfb070131a46b473a94798834707431bdd248e873d9a716cc469d7f21b545dc2eb21d892e8d94ee6544bd82e8112e697eeaecf6a01d31bffaaf37558aec381f8d12c8491ff77ce00a1da4e2fe6ddf4e5dd14fe1ef90102818100dd2b49e13111593e91a882ae522c1363e2b5e3a10e71c4599e32eec56d9d01682983232b582f2e0923dd107e259771382dd7ff738be31cbba5095153a636dd44e8b08f47e044bbf5814aebdcfed33f0a32fc2f62bf3a0ded9d8aed48fc8034debbf5399862ca2bac72d9d4ab70f90a6a246c6cf4a62c9cb887ea776dce57511902818100d61925b811da57c10e444528230bdb0156516b5ca9ff89a9e57da8373bf5911d009bf5e8a6ee0d40edb89f01e638a528ce592e27d3e7f2172ce373a3b510f2f5045a5dd9aa4ae28b088553a5d099f95611447df464da04168d88ba69751046229131b5a820f9215548de643a82a04ad062ddd74a2e2f30d88480b115c2aa372502818031e374dbce14aabbd9615870f7ea27498db717ac99b481e4f1316df8acbc10b82d3cfe6ee58a66e8fae4ffb664c65f6c9bb2b055a1054ed2e8ec4c23014838eb354db654313b6fe6760eaf5b7f43a961a4948c1fcb20ce497e12fb694e43a12968de6cea79c63ec9bc72746d63a3597d0dd04357803069fd99f302938b4ad8e902818100c167f835ff12b2417924dd2074006ab81b84f3aac2fb501e056d6d3f704fd6e64f3d9478b60bc83746488883cbb8922279be003f0463bcc388ce741188292681868c27c9d0d7532d6be61d7966272221c8f9899af45c2a63413a29c3c8778a1401fbd8f167d00677a79b1709f024e350ba6f52e3f532b63a72005b789fe0ea6d02818100cd0855c641e6294a1c05667f043eedf539c38bbd357dd20dacb182c96455593c689eafc7844d2ba8cd86ce77a3f3151aa261434cdb4d21367c9c62f73289aecb2719de0aca9857365eb16cc56bffbd9b28835eaa4499971996e63306bfdfea35c86179bd749992501aa6c0f45c0123ef6a8a3bb4344c198a0046b94c3bf506f5' // pragma: allowlist secret\n const pHcpBase: HealthcareParty = {\n id: pId,\n lastName: '8ed642',\n firstName: 'c9d727',\n publicKey:\n '30820122300d06092a864886f70d01010105000382010f003082010a0282010100b8f7e992be3973d42954ca27da89259961c93cca31c6494b074f6f5992ce7ba1d95fdfaf043d5047b6e492c735d68344e0348f08683f1dae728d1e86c439c8498613ec7c8fb54930afbb9f45c74f4d312ecf5d989cb2edd96f887551792094ddd2d18a4c2dc2107c9b044b755f93f8d63e956e1ff0299fa9ed190845f7f5f69dc510df005bd929fb4fed33b30d6e699e0632485cc4180cf5a130357cf64233a680a1a1cc6b6761188192734916cabda14bb954ba3807b84c92f078fe83eea31260390356a8d53853148191144a4584fef02d28bc8353d3c33a87b156396e5fcb7994165da48138db3a3b986fe1c12d46273a218af63b42514690fbb161a5179d0203010001', // pragma: allowlist secret\n }\n const pUserBase: User = {\n id: randomUUID(),\n name: pLogin,\n status: User.StatusEnum.ACTIVE,\n login: pLogin,\n passwordHash: pPassword,\n healthcarePartyId: pId,\n email: pLogin,\n }\n const aId = randomUUID()\n const aLogin = `childA-${randomUUID()}`\n const aPassword = randomUUID()\n const aPrivateKey =\n '308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100e92f6acc40dbf839fa26e14579fcb68b5e8530f7bfada96338d4f986936cf177e242a458cb1811c2c49c469fa84d2c6ba0c0f34ba6e28babfaff863ff9f3938741d4a41b936143adcff5b396ce12f253e1af424ebd75aa133bdf606b1be51142ee4f5310f4ab46b7a7d706034028f81c462a758f0243d3791d27758bcc8af8010116ee70f1e61eb4526d05d245d631459974eea86b500ad0083e7f196ab9c4926487d92aa2849878f2e4093691d0539b9e880ff6717dbe5e7903141aaf796d74100c42c4d33ac2356df7e3e037accf4495c05f2caf57ae47130b1833f95397e1e9324f2abc1e6af56d7297cf48ea2ba0d990cff2f3b59b1e44efebd4db537ced020301000102820100129e03bed566d42be33a2ea48dcabfd37cc004c13c98e3af3beb8eaee9ebed2d0f2316f667e3d8772b35c3b8eab9cea0e795f356c81d63dd5edacbd325646d7a837367220149e71a97751c73857609ca1cabdea898509508cb49beb88e7c63099ef79bf36302381dfa6e833f2e6496fa8e1df81c04db7971a335d87f7c7660ba6ffb6cc0b3089086df855145b69dba0404ae77b1d533693030e8aa17b851c313d9de7b98a2cd5333fbd1b7d9d7d8d4296c2fc794a50003438eccf0d6dc0a0b34c2695d4f40fa8a5d2de12d5579bc3b33208227cff350413702643f31e0d02317da8165c3f7f1b6a18f00fcea5d981904cb1f5c2bd85d30da963184611f0a06d902818100f6860c1d1c53ad2489bc5e967365e226b25bf292c9ca4f01bbee6d7665f544834f553275e6dc373ed69c942d2e889be2537ae5f5672988c63993bc4f95cbb3dc25b3b8cdf7e274b61532b0e101df22cd54735c2d3f353a4d2d48a1e8dcf11089545b3d8b37f4fa2d3d91129d92e67d9937b065a0bf07c7801df87dd8c1c95f4702818100f2261c810d62345f806345b909e8b1d399d961d5f1bd3c580c96c44ba2e6e532ac93f12cdb25fb6fa9e7a823052c2983611b6c359df98be6c7d0e6377a27cd7f0f67f4568fb72c42d7c3bb13afead3b25a30b7827c1f059d9f75c939fc8608afe2882fdeeb3c292ba45647f373c8ff5719c6da1152c94871b722e8129851a42b028181008fe65945d8d6233833ca27f06c75e957ab3f2ece6e49d06a73b7ce5f914e64eabd313f1e415f044482e3ad3ede6dd188803039f15081971c1659dd4f1b62679fb6c63cb6c5de834012099fe407c2a73ef1efd0bb7cace6564c7b9c3f2050fad51ecf8f92275cb1781cfb04c1c41114f98ddf42c35d1efe5e13a08c5d2d690d5b02818033d7a2fca22fe744970929f13ec4d9e592a7aec18e3ad483895671fa3b8b3180d2dfed9f8bdfaae032410d8749e1359612213bde92cecd7c0045a234386bf31c03e15eb7759762db80b440062c009b8830b50364e54c02f8c71e0191ef9586a099604cd76e07784d06a70e4a79fc8b664b777e527d25e8e3a7b0ca7cc8ad99f70281803b9df4b2e66d849b269300fe42c3136d929fdc184d51283a9fe25772a796ed710b475e85a4e442519a207eeb66e0d89d552798a9b2eb2ebb329109cf4fbce35feba75025a157b57c98776dbe9f04c8937e5cd34021b68ffac95c23c3129967a3aa82ddda35098ba55958e3531fa226825a2685e1ce94353a22a03a1eb9b1a9a0' // pragma: allowlist secret\n const aHcpBase: HealthcareParty = {\n id: aId,\n lastName: '6144e2',\n firstName: '6ca3b4',\n parentId: pId,\n aesExchangeKeys: {\n '30820122300d06092a864886f70d01010105000382010f003082010a0282010100e92f6acc40dbf839fa26e14579fcb68b5e8530f7bfada96338d4f986936cf177e242a458cb1811c2c49c469fa84d2c6ba0c0f34ba6e28babfaff863ff9f3938741d4a41b936143adcff5b396ce12f253e1af424ebd75aa133bdf606b1be51142ee4f5310f4ab46b7a7d706034028f81c462a758f0243d3791d27758bcc8af8010116ee70f1e61eb4526d05d245d631459974eea86b500ad0083e7f196ab9c4926487d92aa2849878f2e4093691d0539b9e880ff6717dbe5e7903141aaf796d74100c42c4d33ac2356df7e3e037accf4495c05f2caf57ae47130b1833f95397e1e9324f2abc1e6af56d7297cf48ea2ba0d990cff2f3b59b1e44efebd4db537ced0203010001': // pragma: allowlist secret\n {\n [pId]: {\n '3b42514690fbb161a5179d0203010001': // pragma: allowlist secret\n '4ca457e66519a3f403e089f56f3838a18af16e47029d33ca40eca6a24d1f213809851920b8d159e3879284e5e8d1e0c64be874261d3e0003c43a21ddab9301f8a54161911d3bebe3b1ee6d2a040ec88caa484b6ffd46200bc6eb1a767f309e960f977b9e82d81a0b4961b517e89f24cbc9d0133f955a8d6f792486b1e5dcd9088fe5ecc07b11230b1960013c914041e5de3e9b3c37fa4c2a44dcf2136aae57e000acfe824dacd900bf6be5f6b4f3c41534237a01e14d728065c586dbfd3eeb81ad070218be3e2f70757e9ca5d940afa0b67e02d41e68c1c10935157bc6bd3c06eda95f23c10ca60b649a5ec32903c2a995c0b97fb40cdf454c53621304b0d5b0', // pragma: allowlist secret\n b59b1e44efebd4db537ced0203010001:\n '50864963c90cc12704b35ec6cd15ee40a2f4fd4dcb1cf287612346eab4df139008adef1c6d778e35aa7cb58251ff34d6bf1b0faa59d5453c328fa381b175143f41ce66463146b9a02d546cea0065bf62d1ce58e27a8d3bb8bebbb97b76c7e0d7a67b481fdc5082e99aa0521026eb89344b9404da04b0a69988e03724421747e47ab544ed2c55d0424f2837e641f9df4f4ece731e38f9a16d056d9fcf442730c50b3cabcdfbd8241677648639af75198bd30ded0f0fa2db0f8ce80cf86350cef278ce1c7a5426262ceebcc6be5579892d8e066763e216e1592f3f5faa13c561f73400549f5ba2bd618fb308ef99d52cc360ce30988af058caca8c23113933f588', // pragma: allowlist secret\n },\n [aId]: {\n b59b1e44efebd4db537ced0203010001:\n '189ab5f91d1401fe4c8d2be8e044dcb80211fbf1f310d154a21e32b2b7c0cca715178b42a9a5bbd136b81eed1158da5c8e600e265b38c2b608127b343f0d8da301d80eb24a620ed64bec091771a092a2072a922c2852de55942cc99ae0f9c609150c9621cbaf27740105b28e33668ad0a960c13f884029bb1c8253d646b503ac597f8dbb6ce79b64e7b3929b3a3b649805fb327c2d855f47947e8d5dbf9aa4a0da56b9c1030e9fb1f415d0ee48d91d11c320d1bcba9b96a50574ab406f84629edbb86c68ca548d9dcdd08b4d63c93b3d654e810baaf0782068bc91934fb19f9ab46d940dd3d3e27fc6ac1bcd47440f098d97a9b454df929ba60ae0aa5efe7861', // pragma: allowlist secret\n },\n },\n },\n publicKey:\n '30820122300d06092a864886f70d01010105000382010f003082010a0282010100e92f6acc40dbf839fa26e14579fcb68b5e8530f7bfada96338d4f986936cf177e242a458cb1811c2c49c469fa84d2c6ba0c0f34ba6e28babfaff863ff9f3938741d4a41b936143adcff5b396ce12f253e1af424ebd75aa133bdf606b1be51142ee4f5310f4ab46b7a7d706034028f81c462a758f0243d3791d27758bcc8af8010116ee70f1e61eb4526d05d245d631459974eea86b500ad0083e7f196ab9c4926487d92aa2849878f2e4093691d0539b9e880ff6717dbe5e7903141aaf796d74100c42c4d33ac2356df7e3e037accf4495c05f2caf57ae47130b1833f95397e1e9324f2abc1e6af56d7297cf48ea2ba0d990cff2f3b59b1e44efebd4db537ced0203010001', // pragma: allowlist secret\n }\n const aUserBase: User = {\n id: randomUUID(),\n name: aLogin,\n status: User.StatusEnum.ACTIVE,\n login: aLogin,\n passwordHash: aPassword,\n healthcarePartyId: aId,\n autoDelegations: {\n all: [pId],\n },\n email: aLogin,\n }\n const bId = randomUUID()\n const bLogin = `childB-${randomUUID()}`\n const bPassword = randomUUID()\n const bPrivateKey =\n '308204bc020100300d06092a864886f70d0101010500048204a6308204a20201000282010100982330dc464b3e9c583affbfece209976bc045f07b22fb44bcb0ebc27bc9d8406b54e380d195e107c1728499a64012b3251c1c85a2516e73b89a07b1929f0c12d44828677135082e8170b9831dd4ff9e988d098731eadd1443813cb5f6af2fe4c2a2706ba6aeb5bb6bb7889be51eebd83bebbb2a0b55a6d69fdeb66894af47edd6f82a8d30629814b82f17cfd1ef75f47d192eb9577c58f14a5e0d2782b13b796b5a3be780a38b0f69f3d00179d13cc23fcec1e919ac05d88c08c693c711384ad9fc7a21ed28d0e5d3865c15db239a5d727d4c52a344975c97379cc5a195ff4f8c1aacbaa67d6d0fd358b6b5d1a4d0575bc57b2d7736108978e3371e9aa0ae8f0203010001028201002a9bac7afc9ae5399f4242cf4b36110e9de8570e1f46704dd374cf4a8425c7115f9e022b59475b23336bf1b4208a1052a8e183217010d358c88a26fe75fc6242c1be45c696bf8dff8c53f838bef9a0ef9774e486bf15b27e12dbd69775b3a1bbb5410e303019fd1eb4efcd6c2fd2a5a5c53e6388466d6210f8ec4474ecb35c76d2c4269d3a585cdce972673c56818015b9f097ff528e26272b76810cb4f8a1ee5ea04ea26f4cf3c6f78b77c5f58d80628f513a4da76cc1e35a6867af1ab76fe0354e549340221d19bfe04783e34f84eca7bd80867134710adc0665a52eb689d2cf6ecb38ca77d84f4feb8c23539e92ac870b3175c174d8f5643aabc0e7ef3cd102818100ba44b38b24e28d9fb85279c0098b4505e0852ba88b54d2cb8b0e77368c1600bb40b4c0f6dee8b97788e082af0f9045dd54f05ee583fffabc473d16272d03c1aef301541176e7a95f948f8d77b6aad087c54f2de713909efdd5d90a8bbec61067172a97480ba844c25cf64a8b1f0698e2f4dd73af798dd8ab329f7f9bf9a0f9ff02818100d11781567bde00a256ac7ef2c4bf10a5b8b2ebab77c941b7665817f17aa496f166ecd89bb4c50c53d4e836b3369edc2f0f49e64f8dbe7ddaf0fb3898075f6e82ab2c69bc925368904ba459ce08a40ce621dceefa78b64d8eb68752d1cc2a53a1db9718ab1a8703333065cf9b8407174c18f8b085e4aebf32a5bf9b259a6bab71028180492352b04f025a039df75c70e80e7442b37ef6be8e3ef72a0ee6d62e67e0f7d68eb8aa9004c4b29659fb75b4d1529fec213ee4b4101981d54dcf91943e5b9c405a9069f7158e2ef625ba1c1d266f79c3e5d88a38927915c4aba4363cdae2a06c2a2f82093af28e5516f56a1da84809de0bb1ac8bf919963ada7cc039795218f70281802b0aceaa31f78263e8b9bbac580a08f04474388564b43e5df5a87ecd4bf4e3c9afe963b1b1e5ba62eb7a1e008866ed66969c1cd81592b82fc0d9c64dad7edcadf374c2137a7fc70fa532a0f603db59786a5223b3d5f399459e977eda0750534507823426cce02c2d76720ee9b1a5100baf3c4a8255900f75ea9ee5de38ca9f510281802c19faaa1e08ac6337c48af1529f8b8685d2582586986b180377aee8cf4eaadcdbb5869c6f994275b0ae3ecc6aa0ead81296ab9a96eecb44f14fcd9e50ef34d9725e97809b3ed2ed6105102c96ea55a096f292a8d9769c05779f303dc6ad3b30c3c9bea749d58636b3977c9c593557c048b2f82e90fead32b5b510966e548e7a' // pragma: allowlist secret\n const bHcpBase: HealthcareParty = {\n id: bId,\n lastName: '95ee22',\n firstName: '2af696',\n parentId: pId,\n aesExchangeKeys: {\n '30820122300d06092a864886f70d01010105000382010f003082010a0282010100982330dc464b3e9c583affbfece209976bc045f07b22fb44bcb0ebc27bc9d8406b54e380d195e107c1728499a64012b3251c1c85a2516e73b89a07b1929f0c12d44828677135082e8170b9831dd4ff9e988d098731eadd1443813cb5f6af2fe4c2a2706ba6aeb5bb6bb7889be51eebd83bebbb2a0b55a6d69fdeb66894af47edd6f82a8d30629814b82f17cfd1ef75f47d192eb9577c58f14a5e0d2782b13b796b5a3be780a38b0f69f3d00179d13cc23fcec1e919ac05d88c08c693c711384ad9fc7a21ed28d0e5d3865c15db239a5d727d4c52a344975c97379cc5a195ff4f8c1aacbaa67d6d0fd358b6b5d1a4d0575bc57b2d7736108978e3371e9aa0ae8f0203010001': // pragma: allowlist secret\n {\n [pId]: {\n '3b42514690fbb161a5179d0203010001': // pragma: allowlist secret\n '5e186cec6d6ddb277aa5421a345045f5f44aa125844e833529fccfeb3a002dd4aef78d84b5b8710ff0aa375436e2abdea07a2cb186cd914fa8b8fb86ab1201b109d802927b49517322ac6521600a123ee03d9383154b6f0fa0e99a8ca6e73e07ceed4aeb835649a850316c5585b2a69ac6703c7154f2db981913bac36a0cea515c70c505d1dc3a7e3a6db519cf7b68737a80ad102cc575959b08fbe327644e7d1b7da0737bfa6ededdd7bf0538fd3dc040ac57937bebdf3146a566c2619314935bc610e900b9c350fcf21a9b20c47f0ee25112578dc210b6b17c4cad9687d2bd9abab12f03f8b778b74186ac3c61d57058037d0e00903c74d2eaa8b2fdb90e3f', // pragma: allowlist secret\n '36108978e3371e9aa0ae8f0203010001': // pragma: allowlist secret\n '89764feb4d23d8313d58c0568088ecf9f320dd285eb762eaee8593a9ecc884a54e4eb6cd93a87f1383f345b94b8a7f1d20dda33d972ab4460aef742d44837648403234700a5a9f85032b025c533aebdc7bea07dec17c7a1737a51f873ec36c689a29b3314fa2d0f77d7e83e71e5a1de1392a6e92fb9881d811253f2bc00db0798e213899a85bcf0bafeaf8b972c40b1a0d1dd3109e6a8bc9309caa5ada9bc41ea62c72fbdf7cf49cbbe15cd048e6d614a4d65e09f5bed014975ea19c160e3754abd9031e8a41283fa369fa621685aee16c5a5d18a1811fde27869cb156a00fe28ae42c9ff498f2c3dd88a392ac9d68d9885556effe62850681fa8fbe5e02781f', // pragma: allowlist secret\n },\n },\n },\n publicKey:\n '30820122300d06092a864886f70d01010105000382010f003082010a0282010100982330dc464b3e9c583affbfece209976bc045f07b22fb44bcb0ebc27bc9d8406b54e380d195e107c1728499a64012b3251c1c85a2516e73b89a07b1929f0c12d44828677135082e8170b9831dd4ff9e988d098731eadd1443813cb5f6af2fe4c2a2706ba6aeb5bb6bb7889be51eebd83bebbb2a0b55a6d69fdeb66894af47edd6f82a8d30629814b82f17cfd1ef75f47d192eb9577c58f14a5e0d2782b13b796b5a3be780a38b0f69f3d00179d13cc23fcec1e919ac05d88c08c693c711384ad9fc7a21ed28d0e5d3865c15db239a5d727d4c52a344975c97379cc5a195ff4f8c1aacbaa67d6d0fd358b6b5d1a4d0575bc57b2d7736108978e3371e9aa0ae8f0203010001', // pragma: allowlist secret\n }\n const bUserBase: User = {\n id: randomUUID(),\n name: bLogin,\n status: User.StatusEnum.ACTIVE,\n login: bLogin,\n passwordHash: bPassword,\n groupId: 'test-group',\n healthcarePartyId: bId,\n autoDelegations: {\n all: [pId],\n },\n email: bLogin,\n }\n const patientConfidentialSecretId = '24cd8cf5-0958-4ee9-8e90-95f3d25a47d7'\n const patientBase: Patient = {\n id: randomUUID(),\n firstName: 'John',\n lastName: 'Doe',\n delegations: {\n [aId]: [\n {\n owner: aId,\n delegatedTo: aId,\n key: '4bd1316d494e858496f1d6c1200726cb76c7ff98fb47eddb1c0bf5b79712230db3f02bdf60599816e0601628ee349674a0509720e9972d87b2370b60bcbbb19adb2980bc1ab5bab8b9c8adc5516d39d0cf2d6c373fe7285ce0f1018058e52fcc', // pragma: allowlist secret\n tags: ['confidential'],\n },\n {\n owner: aId,\n delegatedTo: aId,\n key: '6121912dea437ddaf92c41a43deba576976a2b7c10c1cbba79624634ded8bb5d0210db5e339e3e26d33e6e2d18d6b8acc91f8415e5ab488b9227f7c6f6f370873f1d5b5ff3afd28dfe6e47ed10b0cb435676a4db039469a50547f3e1e515fc63', // pragma: allowlist secret\n },\n ],\n [pId]: [\n {\n owner: aId,\n delegatedTo: pId,\n key: '0b293a861d76b21928c6689fb80c373f16bfbe8269ef201b5af35ff4634e51af1c5d3c535c384efea3126acee3572b815db950c52298b1ee99868041641110100c51ad3bc6d0bafddd5021b50b8e0fd16c44f5fd05617eae4f5a00c090c0ccfb', // pragma: allowlist secret\n },\n ],\n },\n encryptionKeys: {\n [aId]: [\n {\n owner: aId,\n delegatedTo: aId,\n key: '42e625cb8930ca763f6b604d08775b4231e9414fa953feeafbd7cfc6acc138bdbf5013aa211935f9f429a627db5d41efa617b2ae9d46f93d83db73b36dab7892c07b03408ee4ab50974b0d4081162b4e9a2a448ce00e35d05aac4d7e675e99b3', // pragma: allowlist secret\n },\n ],\n [pId]: [\n {\n owner: aId,\n delegatedTo: pId,\n key: '194ee902b4780178fd88ffddd1e0744537ddf952d306dfe1123b14bec4405dc1f6b9aea7444cc74f5acca0d18062c0e12d7d9bb6c7b7bff27efb681c7e5ca52f25797f45207f63c13778637a40a541a2e33d79dc1660d7f898d69c92a93aedcf', // pragma: allowlist secret\n },\n ],\n },\n encryptedSelf: 'jgAFAlmd2QStXpOt3LnIhs4upJv2e10fp0u6/PburW7mq1r3vo/Q5/a4Yk7EWXG7oydMWb2i1UCCiNN80czGdA==', // pragma: allowlist secret\n }\n\n const testSetupApi = await initMasterApi(env)\n await testSetupApi.healthcarePartyApi.createHealthcareParty(pHcpBase)\n const pUser = await testSetupApi.userApi.createUser(pUserBase)\n await testSetupApi.healthcarePartyApi.createHealthcareParty(aHcpBase)\n const aUser = await testSetupApi.userApi.createUser(aUserBase)\n await testSetupApi.healthcarePartyApi.createHealthcareParty(bHcpBase)\n const bUser = await testSetupApi.userApi.createUser(bUserBase)\n const pStorage = await testStorageWithKeys([\n {\n dataOwnerId: pHcpBase.id!,\n pairs: [{ keyPair: { privateKey: pPrivateKey, publicKey: pHcpBase.publicKey! }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const aStorage = await testStorageWithKeys([\n {\n dataOwnerId: aHcpBase.id!,\n pairs: [{ keyPair: { privateKey: aPrivateKey, publicKey: aHcpBase.publicKey! }, shaVersion: ShaVersion.Sha1 }],\n },\n {\n dataOwnerId: pHcpBase.id!,\n pairs: [{ keyPair: { privateKey: pPrivateKey, publicKey: pHcpBase.publicKey! }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const bStorage = await testStorageWithKeys([\n {\n dataOwnerId: bHcpBase.id!,\n pairs: [{ keyPair: { privateKey: bPrivateKey, publicKey: bHcpBase.publicKey! }, shaVersion: ShaVersion.Sha1 }],\n },\n {\n dataOwnerId: pHcpBase.id!,\n pairs: [{ keyPair: { privateKey: pPrivateKey, publicKey: pHcpBase.publicKey! }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const pApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: pLogin, password: pPassword },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: pStorage.storage,\n keyStorage: pStorage.keyStorage,\n entryKeysFactory: pStorage.keyFactory,\n disableParentKeysInitialisation: false,\n }\n )\n const aApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: aLogin, password: aPassword },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: aStorage.storage,\n keyStorage: aStorage.keyStorage,\n entryKeysFactory: aStorage.keyFactory,\n disableParentKeysInitialisation: false,\n }\n )\n const bApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: bLogin, password: bPassword },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: bStorage.storage,\n keyStorage: bStorage.keyStorage,\n entryKeysFactory: bStorage.keyFactory,\n disableParentKeysInitialisation: false,\n }\n )\n const xInfo = await createNewHcpApi(env)\n const x2Info = await createNewHcpApi(env)\n const apis = { a: aApi, b: bApi, p: pApi, x: xInfo.api, x2: x2Info.api }\n const xUser = xInfo.user\n const xCredentials = xInfo.credentials\n const x2User = x2Info.user\n const x2Credentials = x2Info.credentials\n const patient = await new IccPatientApi(env.iCureUrl, {}, aApi.authApi.authenticationProvider, fetch).createPatient(patientBase)\n const ids = {\n a: aId,\n b: bId,\n p: pId,\n x: xCredentials.dataOwnerId,\n x2: x2Credentials.dataOwnerId,\n }\n console.log(JSON.stringify(ids, undefined, 2))\n return {\n apis,\n ids,\n users: {\n a: aUser,\n b: bUser,\n p: pUser,\n x: xUser,\n x2: x2User,\n },\n patient,\n patientConfidentialSecretId,\n patientNote: 'This is just a test patient',\n }\n }\n\n /*\n * Entity E with legacy metadata created by A and shared with P.\n * There is also a confidential secret id (known by A but not P).\n * B wants to share with X as read only.\n * Expected outcome:\n * - A root secure delegation B->B\n * - A delegation B->P\n * - Through the delegation B->P A and P can access all the legacy metadata available to P (but not the confidential secret id known by A)\n * - A delegation from B->X\n * - Through B->X X can access only the shared information and has read access only\n *\n * Now A wants to share with X2.\n * Expected outcome:\n * - A new root secure delegation A->A is available, which gives access to the confidential secret id\n * - A delegation A->X2 with the shared information.\n * - Parents of the new delegation are the new A->A root delegation and the existing A->P delegation.\n * - B and P still can't access the confidential secret id.\n */\n it('sharing data as a child of a parent with legacy access should work', async () => {\n console.log('Creating test data')\n const { apis, ids, patient, patientConfidentialSecretId, users, patientNote } = await createTestDataAndApis()\n console.log('Starting test')\n const secretIdsKnownByA = new Set(await apis.a.patientApi.decryptSecretIdsOf(patient))\n const secretIdsKnownByB = new Set(await apis.b.patientApi.decryptSecretIdsOf(patient))\n expect(secretIdsKnownByB.size).to.eq(1)\n expect(secretIdsKnownByB.has(patientConfidentialSecretId)).to.be.false\n expect(secretIdsKnownByA.size).to.eq(2)\n expect(secretIdsKnownByA.has(patientConfidentialSecretId)).to.be.true\n expect(secretIdsKnownByA.has([...secretIdsKnownByB][0])).to.be.true\n const sharedPatient = await apis.b.patientApi.shareWith(ids.x, patient, [...secretIdsKnownByB], {\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n })\n const secureDelegations = Object.values(sharedPatient.securityMetadata?.secureDelegations ?? {})\n expect(secureDelegations).to.have.length(3)\n expect(secureDelegations.find((d) => d.delegator === ids.b && d.delegate === ids.b)).to.not.be.undefined\n expect(secureDelegations.find((d) => d.delegator === ids.b && d.delegate === ids.p)).to.not.be.undefined\n const sharedPatientWithoutLegacyDetails: Patient = { ...sharedPatient, delegations: {}, encryptionKeys: {} }\n expect(await apis.a.patientApi.getEncryptionKeysOf(sharedPatientWithoutLegacyDetails)).to.have.length(1)\n expect(await apis.a.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails)).to.have.members([...secretIdsKnownByB])\n expect(secureDelegations.find((d) => d.delegator === ids.b && d.delegate === ids.x)).to.not.be.undefined\n expect((await apis.x.patientApi.getPatientWithUser(users.x, patient.id!)).note).to.eq(patientNote)\n expect(await apis.x.cryptoApi.xapi.hasWriteAccess({ entity: sharedPatient, type: EntityWithDelegationTypeName.Patient })).to.be.false\n expect(\n await apis.x.patientApi.modifyPatientWithUser(users.x, { ...sharedPatient, firstName: 'New name' }).then(\n () => true,\n () => false\n )\n ).to.be.false\n expect(await apis.x.patientApi.decryptSecretIdsOf(sharedPatient)).to.have.members([...secretIdsKnownByB])\n const sharedPatient2 = await apis.a.patientApi.shareWith(ids.x2, sharedPatient, [...secretIdsKnownByB], {\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n })\n const secureDelegations2 = Object.values(sharedPatient2.securityMetadata?.secureDelegations ?? {})\n expect(secureDelegations2).to.have.length(5)\n expect(secureDelegations2.find((d) => d.delegator === ids.a && d.delegate === ids.a)).to.not.be.undefined\n const secureDelegationAtoX2 = secureDelegations2.find((d) => d.delegator === ids.a && d.delegate === ids.x2)\n expect(secureDelegationAtoX2).to.not.be.undefined\n expect(secureDelegationAtoX2?.parentDelegations).to.have.length(2)\n expect(await apis.b.patientApi.decryptSecretIdsOf(sharedPatient2)).to.have.members([...secretIdsKnownByB])\n })\n\n /*\n * Entity E with legacy metadata created by A and shared with P.\n * There is also a confidential secret id (known by A but not P).\n * A wants to share with X as read only.\n * Expected outcome:\n * - A root secure delegation for A\n * - A->A includes the confidential secret id known by A\n * - A delegation from A to P\n * - Through the delegation A->P A and P can access all the legacy metadata available to P (but not the confidential secret id)\n */\n it('sharing data created with legacy api by the same user ', async () => {\n console.log('Creating test data')\n const { apis, ids, patient, patientConfidentialSecretId, users, patientNote } = await createTestDataAndApis()\n console.log('Starting test')\n const secretIdsKnownByA = new Set(await apis.a.patientApi.decryptSecretIdsOf(patient))\n const secretIdsKnownByB = new Set(await apis.b.patientApi.decryptSecretIdsOf(patient))\n const sharedPatient = await apis.a.patientApi.shareWith(ids.x, patient, [...secretIdsKnownByB], {\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n })\n const secureDelegations = Object.values(sharedPatient.securityMetadata?.secureDelegations ?? {})\n expect(secureDelegations).to.have.length(3)\n expect(secureDelegations.find((d) => d.delegator === ids.a && d.delegate === ids.a)).to.not.be.undefined\n expect(secureDelegations.find((d) => d.delegator === ids.a && d.delegate === ids.p)).to.not.be.undefined\n expect(secureDelegations.find((d) => d.delegator === ids.a && d.delegate === ids.x)).to.not.be.undefined\n const sharedPatientWithoutLegacyDetails: Patient = { ...sharedPatient, delegations: {}, encryptionKeys: {} }\n console.log(await apis.a.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails))\n console.log(await apis.b.patientApi.decryptSecretIdsOf(sharedPatient))\n console.log(await apis.b.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails))\n console.log(await apis.x.patientApi.decryptSecretIdsOf(sharedPatient))\n expect(await apis.a.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails)).to.have.members([...secretIdsKnownByA])\n expect(await apis.b.patientApi.decryptSecretIdsOf(sharedPatient)).to.have.members([...secretIdsKnownByB])\n expect(await apis.b.patientApi.decryptSecretIdsOf(sharedPatientWithoutLegacyDetails)).to.have.members([...secretIdsKnownByB])\n expect(await apis.x.patientApi.decryptSecretIdsOf(sharedPatient)).to.have.members([...secretIdsKnownByB])\n console.log(JSON.stringify(sharedPatient, undefined, 2))\n })\n})\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { IcureApi, IcureApiOptions } from '../../icc-x-api';
|
|
2
|
+
import { IcureApi as TestSetupApi } from '@icure/api';
|
|
2
3
|
import { User } from '../../icc-api/model/User';
|
|
3
4
|
import { TestVars, UserDetails } from '@icure/test-setup/types';
|
|
4
5
|
import { EnvInitializer } from '@icure/test-setup/decorators';
|
|
@@ -59,6 +60,7 @@ export declare function createNewHcpWithoutKeyAndParentWithKey(env: TestVars, pr
|
|
|
59
60
|
childDataOwnerId: string;
|
|
60
61
|
childPassword: string;
|
|
61
62
|
}>;
|
|
63
|
+
export declare function testSetupMasterApi(env: TestVars): Promise<TestSetupApi>;
|
|
62
64
|
export type UserInManyGroupsDetails = {
|
|
63
65
|
user1: User;
|
|
64
66
|
user2: User;
|
package/test/utils/test_utils.js
CHANGED
|
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
};
|
|
11
11
|
var _a, _b, _c, _d;
|
|
12
12
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
-
exports.itNoLite = exports.describeNoLite = exports.isLiteTest = exports.createUserInMultipleGroups = exports.createNewHcpWithoutKeyAndParentWithKey = exports.createHcpHierarchyApis = exports.createNewPatientApi = exports.createNewHcpApi = exports.getApiAndAddPrivateKeysForUser = exports.TestUtils = exports.getEnvironmentInitializer = exports.deviceUsername = exports.patUsername = exports.hcp3Username = exports.hcp2Username = exports.hcp1Username = exports.setLocalStorage = exports.getTempEmail = void 0;
|
|
13
|
+
exports.itNoLite = exports.describeNoLite = exports.isLiteTest = exports.createUserInMultipleGroups = exports.testSetupMasterApi = exports.createNewHcpWithoutKeyAndParentWithKey = exports.createHcpHierarchyApis = exports.createNewPatientApi = exports.createNewHcpApi = exports.getApiAndAddPrivateKeysForUser = exports.TestUtils = exports.getEnvironmentInitializer = exports.deviceUsername = exports.patUsername = exports.hcp3Username = exports.hcp2Username = exports.hcp1Username = exports.setLocalStorage = exports.getTempEmail = void 0;
|
|
14
14
|
const icc_x_api_1 = require("../../icc-x-api");
|
|
15
15
|
const os_1 = require("os");
|
|
16
16
|
const util_1 = require("util");
|
|
@@ -337,6 +337,7 @@ function testSetupMasterApi(env) {
|
|
|
337
337
|
},
|
|
338
338
|
}, crypto_1.webcrypto, fetch);
|
|
339
339
|
}
|
|
340
|
+
exports.testSetupMasterApi = testSetupMasterApi;
|
|
340
341
|
function createUserInMultipleGroups(env) {
|
|
341
342
|
return __awaiter(this, void 0, void 0, function* () {
|
|
342
343
|
const primitives = new icc_x_api_1.CryptoPrimitives(crypto_1.webcrypto);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test_utils.js","sourceRoot":"","sources":["../../../test/utils/test_utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,+CAWwB;AACxB,2BAA2B;AAC3B,+BAA+C;AAC/C,+BAAiC;AACjC,mCAAkC;AAClC,uCAAmC;AACnC,oCAAqD;AACrD,+CAAmD;AACnD,iEAA6D;AAC7D,mDAA+C;AAC/C,uDAAkE;AAClE,mDAAgF;AAEhF,4BAAyB;AACzB,yDAA8D;AAC9D,2CAA0C;AAC1C,iCAAsD;AAGtD,SAAgB,YAAY;IAC1B,OAAO,GAAG,IAAA,SAAI,GAAE,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,YAAY,CAAA;AAC9C,CAAC;AAFD,oCAEC;AAED,SAAgB,eAAe,CAAC,KAAoE;IAClG,CAAC;IAAC,MAAc,CAAC,YAAY,GAAG,IAAI,CAAC,OAAO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aVersion,\n ua2hex,\n} from '../../icc-x-api'\nimport { tmpdir } from 'os'\nimport { TextDecoder, TextEncoder } from 'util'\nimport { v4 as uuid } from 'uuid'\nimport { webcrypto } from 'crypto'\nimport { TestApi } from './TestApi'\nimport { IcureApi as TestSetupApi } from '@icure/api'\nimport { testStorageWithKeys } from './TestStorage'\nimport { TestCryptoStrategies } from './TestCryptoStrategies'\nimport { User } from '../../icc-api/model/User'\nimport { TestEnvironmentBuilder } from '@icure/test-setup/builder'\nimport { getEnvVariables, TestVars, UserDetails } from '@icure/test-setup/types'\nimport { EnvInitializer } from '@icure/test-setup/decorators'\nimport 'isomorphic-fetch'\nimport { createPatientUser } from '@icure/test-setup/creation'\nimport { IccUserApi } from '../../icc-api'\nimport { Context, describe, Suite, Test } from 'mocha'\nimport { Group } from '../../icc-api/model/Group'\n\nexport function getTempEmail(): string {\n return `${uuid().substring(0, 8)}@icure.com`\n}\n\nexport function setLocalStorage(fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>) {\n ;(global as any).localStorage = new (require('node-localstorage').LocalStorage)(tmpdir(), 5 * 1024 ** 3)\n ;(global as any).fetch = fetch\n ;(global as any).Storage = ''\n ;(global as any).TextDecoder = TextDecoder\n ;(global as any).TextEncoder = TextEncoder\n ;(global as any).headers = Headers\n}\n\nexport const hcp1Username = process.env.ICURE_TS_TEST_HCP_USER ?? getTempEmail()\nexport const hcp2Username = process.env.ICURE_TS_TEST_HCP_2_USER ?? getTempEmail()\nexport const hcp3Username = process.env.ICURE_TS_TEST_HCP_3_USER ?? getTempEmail()\nexport const patUsername = process.env.ICURE_TS_TEST_PAT_USER ?? getTempEmail()\n\nexport const deviceUsername = getTempEmail()\n\nlet cachedInitializer: EnvInitializer | undefined\n\nexport async function getEnvironmentInitializer(): Promise<EnvInitializer> {\n if (!cachedInitializer) {\n const env = getEnvVariables()\n const scratchDir = 'test/scratch'\n const baseEnvironment =\n env.testEnvironment === 'docker' || env.testEnvironment === 'oss'\n ? new TestEnvironmentBuilder().setUpDockerEnvironment(scratchDir, ['mock'])\n : new TestEnvironmentBuilder()\n cachedInitializer = await baseEnvironment\n .withGroup(fetch, {\n patient: ['BASIC_USER', 'BASIC_DATA_OWNER'],\n hcp: [\n 'BASIC_USER',\n 'BASIC_DATA_OWNER',\n 'PATIENT_USER_MANAGER',\n 'HIERARCHICAL_DATA_OWNER',\n 'TOPIC_MANAGER',\n 'TOPIC_PARTICIPANT',\n 'LEGACY_MESSAGE_MANAGER',\n ],\n device: ['BASIC_USER', 'BASIC_DATA_OWNER'],\n user: ['BASIC_USER'],\n })\n .withMasterUser(fetch)\n .addHcp({ login: hcp1Username })\n .addHcp({ login: hcp2Username })\n .addHcp({ login: hcp3Username })\n .addPatient({ login: patUsername })\n .addDevice({ login: deviceUsername })\n .withSafeguard()\n .withEnvironmentSummary()\n .build()\n }\n return cachedInitializer\n}\n\nexport namespace TestUtils {\n export async function initApi(envVars: TestVars, userName: string = hcp1Username, options?: IcureApiOptions): Promise<IcureApi> {\n return await getApiAndAddPrivateKeysForUser(envVars.iCureUrl, envVars.dataOwnerDetails[userName], options)\n }\n\n export async function initMasterApi(envVars: TestVars, options?: IcureApiOptions): Promise<IcureApi> {\n return await getApiAndAddPrivateKeysForUser(envVars.iCureUrl, envVars.masterHcp!, options)\n }\n}\n\nexport async function getApiAndAddPrivateKeysForUser(iCureUrl: string, details: UserDetails, options?: IcureApiOptions) {\n const RSA = new RSAUtils(webcrypto as any)\n const keys = {\n publicKey: await RSA.importKey('spki', hex2ua(details.publicKey), ['encrypt'], ShaVersion.Sha1),\n privateKey: await RSA.importKey('pkcs8', hex2ua(details.privateKey), ['decrypt'], ShaVersion.Sha1),\n }\n return await TestApi(iCureUrl, details.user, details.password, webcrypto as any, keys, options)\n}\n\nasync function createHealthcarePartyUser(\n api: TestSetupApi,\n userLogin: string,\n userToken: string,\n publicKey?: string,\n privateKey?: string\n): Promise<UserDetails> {\n const { publicKey: newPublicKey, privateKey: newPrivateKey } = await api.cryptoApi.RSA.generateKeyPair()\n\n const publicKeyHex = !!publicKey && !!privateKey ? publicKey : ua2hex(await api.cryptoApi.RSA.exportKey(newPublicKey, 'spki'))\n const privateKeyHex = !!publicKey && !!privateKey ? privateKey : ua2hex(await api.cryptoApi.RSA.exportKey(newPrivateKey, 'pkcs8'))\n\n const hcp = await api.healthcarePartyApi.createHealthcareParty({\n id: uuid(),\n firstName: uuid().substring(0, 6),\n lastName: uuid().substring(0, 6),\n publicKey: publicKeyHex,\n })\n const hcpUser = await api.userApi.createUser(\n new User({\n id: uuid(),\n name: userLogin,\n login: userLogin,\n email: userLogin,\n healthcarePartyId: hcp.id,\n })\n )\n const token = await api.userApi.getToken(hcpUser.id!, uuid(), 24 * 60 * 60, userToken)\n return {\n user: hcpUser.login!,\n dataOwnerId: hcp.id!,\n password: token,\n publicKey: publicKeyHex,\n privateKey: privateKeyHex,\n }\n}\n\nexport async function createNewHcpApi(env: TestVars): Promise<{\n api: IcureApi\n credentials: UserDetails\n user: User\n}> {\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const credentials = await createHealthcarePartyUser(initialisationApi, `user-${primitives.randomUuid()}`, primitives.randomUuid())\n const storage = await testStorageWithKeys([\n {\n dataOwnerId: credentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: credentials.privateKey, publicKey: credentials.publicKey }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const api = await IcureApi.initialise(\n env.iCureUrl,\n { username: credentials.user, password: credentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: storage.storage,\n keyStorage: storage.keyStorage,\n entryKeysFactory: storage.keyFactory,\n }\n )\n return { api, credentials, user: await api.userApi.getCurrentUser() }\n}\n\nexport async function createNewPatientApi(env: TestVars): Promise<{\n api: IcureApi\n credentials: UserDetails\n user: User\n}> {\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const credentials = await createPatientUser(initialisationApi, `user-${primitives.randomUuid()}`, primitives.randomUuid())\n const storage = await testStorageWithKeys([\n {\n dataOwnerId: credentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: credentials.privateKey, publicKey: credentials.publicKey }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const api = await IcureApi.initialise(\n env.iCureUrl,\n { username: credentials.user, password: credentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: storage.storage,\n keyStorage: storage.keyStorage,\n entryKeysFactory: storage.keyFactory,\n }\n )\n return { api, credentials, user: await api.userApi.getCurrentUser() }\n}\n\n/**\n * Creates a hierarchy of HCPs with the following structure:\n * grand HCP -+-> parent HCP ---> child HCP\n * |\n * +-> child2 HCP\n */\nexport async function createHcpHierarchyApis(\n env: TestVars,\n setupAutodelegations: boolean = true,\n disableParentKeysInitialisation: boolean = false\n): Promise<{\n grandApi: IcureApi\n grandUser: User\n grandCredentials: UserDetails\n parentApi: IcureApi\n parentUser: User\n parentCredentials: UserDetails\n childApi: IcureApi\n childUser: User\n childCredentials: UserDetails\n child2Api: IcureApi\n child2User: User\n child2Credentials: UserDetails\n}> {\n const shaVersion = ShaVersion.Sha1\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const grandCredentials = await createHealthcarePartyUser(initialisationApi, `grand-${primitives.randomUuid()}`, primitives.randomUuid())\n const parentCredentials = await createHealthcarePartyUser(initialisationApi, `parent-${primitives.randomUuid()}`, primitives.randomUuid())\n const childCredentials = await createHealthcarePartyUser(initialisationApi, `child-${primitives.randomUuid()}`, primitives.randomUuid())\n const child2Credentials = await createHealthcarePartyUser(initialisationApi, `child2-${primitives.randomUuid()}`, primitives.randomUuid())\n await initialisationApi.healthcarePartyApi.modifyHealthcareParty({\n ...(await initialisationApi.healthcarePartyApi.getHealthcareParty(parentCredentials.dataOwnerId)),\n parentId: grandCredentials.dataOwnerId,\n })\n await initialisationApi.healthcarePartyApi.modifyHealthcareParty({\n ...(await initialisationApi.healthcarePartyApi.getHealthcareParty(childCredentials.dataOwnerId)),\n parentId: parentCredentials.dataOwnerId,\n })\n await initialisationApi.healthcarePartyApi.modifyHealthcareParty({\n ...(await initialisationApi.healthcarePartyApi.getHealthcareParty(child2Credentials.dataOwnerId)),\n parentId: grandCredentials.dataOwnerId,\n })\n const grandStorage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const grandApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: grandCredentials.user, password: grandCredentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: grandStorage.storage,\n keyStorage: grandStorage.keyStorage,\n entryKeysFactory: grandStorage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const parentStorage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: parentCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: parentCredentials.privateKey, publicKey: parentCredentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const parentApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: parentCredentials.user, password: parentCredentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: parentStorage.storage,\n keyStorage: parentStorage.keyStorage,\n entryKeysFactory: parentStorage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const parentUser = setupAutodelegations\n ? await parentApi.userApi.modifyUser({\n ...(await parentApi.userApi.getCurrentUser()),\n autoDelegations: { all: [grandCredentials.dataOwnerId] },\n })\n : await parentApi.userApi.getCurrentUser()\n const childStorage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: parentCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: parentCredentials.privateKey, publicKey: parentCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: childCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: childCredentials.privateKey, publicKey: childCredentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const childApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: childCredentials.user, password: childCredentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: childStorage.storage,\n keyStorage: childStorage.keyStorage,\n entryKeysFactory: childStorage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const childUser = setupAutodelegations\n ? await childApi.userApi.modifyUser({\n ...(await childApi.userApi.getCurrentUser()),\n autoDelegations: { all: [grandCredentials.dataOwnerId, parentCredentials.dataOwnerId] },\n })\n : await childApi.userApi.getCurrentUser()\n const child2Storage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: child2Credentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: child2Credentials.privateKey, publicKey: child2Credentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const child2Api = await IcureApi.initialise(\n env.iCureUrl,\n { username: child2Credentials.user, password: child2Credentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: child2Storage.storage,\n keyStorage: child2Storage.keyStorage,\n entryKeysFactory: child2Storage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const child2User = setupAutodelegations\n ? await child2Api.userApi.modifyUser({\n ...(await child2Api.userApi.getCurrentUser()),\n autoDelegations: { all: [grandCredentials.dataOwnerId] },\n })\n : await child2Api.userApi.getCurrentUser()\n return {\n grandApi,\n grandUser: await grandApi.userApi.getCurrentUser(),\n grandCredentials,\n parentApi,\n parentUser,\n parentCredentials,\n childApi,\n childUser,\n childCredentials,\n child2Api,\n child2User,\n child2Credentials,\n }\n}\n\n/**\n * Create a parent HCP with a key and a child HCP without any initialised key\n */\nexport async function createNewHcpWithoutKeyAndParentWithKey(\n env: TestVars,\n props: {\n initialiseEmptyKeyForChild?: boolean\n } = {}\n): Promise<{\n parentCredentials: UserDetails\n childUser: string\n childDataOwnerId: string\n childPassword: string\n}> {\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const parentCredentials = await createHealthcarePartyUser(initialisationApi, `parent-${primitives.randomUuid()}`, primitives.randomUuid())\n const childUser = uuid() + '@email.com'\n const childPassword = uuid()\n const childHcp = {\n id: uuid(),\n firstName: uuid().substring(0, 6),\n lastName: uuid().substring(0, 6),\n parentId: parentCredentials.dataOwnerId,\n publicKey: undefined as string | undefined,\n }\n if (props.initialiseEmptyKeyForChild) {\n childHcp.publicKey = ''\n }\n await initialisationApi.healthcarePartyApi.createHealthcareParty(childHcp)\n await initialisationApi.userApi.createUser(\n new User({\n id: uuid(),\n name: childUser,\n login: childUser,\n email: childUser,\n passwordHash: childPassword,\n healthcarePartyId: childHcp.id,\n })\n )\n return {\n parentCredentials,\n childUser,\n childPassword,\n childDataOwnerId: childHcp.id!,\n }\n}\n\nfunction testSetupMasterApi(env: TestVars): Promise<TestSetupApi> {\n return TestSetupApi.initialise(\n env.iCureUrl,\n { username: env.masterHcp!.user, password: env.masterHcp!.password },\n {\n generateNewKeyForDataOwner(): Promise<boolean> {\n return Promise.resolve(true)\n },\n recoverAndVerifySelfHierarchyKeys(): never {\n throw new Error('Unsupported')\n },\n verifyDelegatePublicKeys(delegate: any, publicKeys: string[]): Promise<string[]> {\n return Promise.resolve(publicKeys)\n },\n },\n webcrypto as any,\n fetch\n )\n}\n\nexport type UserInManyGroupsDetails = {\n user1: User\n user2: User\n group3: Group\n userPw3: string\n user3: User\n group2: Group\n group1: Group\n userPw12: string\n userLogin: string\n}\nexport async function createUserInMultipleGroups(env: TestVars): Promise<UserInManyGroupsDetails> {\n const primitives = new CryptoPrimitives(webcrypto as any)\n const userGroup1Id: string = primitives.randomUuid() // Same username-pw as group 2\n const userGroup2Id: string = primitives.randomUuid() // Same username-pw as group 1\n const userGroup3Id: string = primitives.randomUuid() // Same username as group 1/2, different pw\n const userLogin: string = `maria-${primitives.randomUuid()}@pompei.it`\n const userPw12: string = `geppetto-${primitives.randomUuid()}`\n const userPw3: string = `pinocchio-${primitives.randomUuid()}`\n const user1Id: string = primitives.randomUuid()\n const user2Id: string = primitives.randomUuid()\n const user3Id: string = primitives.randomUuid()\n const api = await BasicApis(env.iCureUrl, { username: 'john', password: 'LetMeIn' }, webcrypto as any, fetch) // pragma: allowlist secret\n const group1 = await api.groupApi.createGroup(\n userGroup1Id,\n `test-group-1-${primitives.randomUuid()}`,\n primitives.randomUuid(),\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n {}\n )\n const group2 = await api.groupApi.createGroup(\n userGroup2Id,\n `test-group-2-${primitives.randomUuid()}`,\n primitives.randomUuid(),\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n {}\n )\n const group3 = await api.groupApi.createGroup(\n userGroup3Id,\n `test-group-3-${primitives.randomUuid()}`,\n primitives.randomUuid(),\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n {}\n )\n const user1 = await api.userApi.createUserInGroup(userGroup1Id, {\n id: user1Id,\n name: userLogin,\n login: userLogin,\n email: userLogin,\n passwordHash: userPw12,\n })\n const user2 = await api.userApi.createUserInGroup(userGroup2Id, {\n id: user2Id,\n name: userLogin,\n login: userLogin,\n email: userLogin,\n passwordHash: userPw12,\n })\n const user3 = await api.userApi.createUserInGroup(userGroup3Id, {\n id: user3Id,\n name: userLogin,\n login: userLogin,\n email: userLogin,\n passwordHash: userPw3,\n })\n console.log(`Waiting for user to be created - ${userLogin}`)\n await retry(\n async () => {\n await new IccUserApi(env.iCureUrl, {}, new BasicAuthenticationProvider(`${userGroup1Id}/${user1Id}`, userPw12), fetch).getCurrentUser()\n await new IccUserApi(env.iCureUrl, {}, new BasicAuthenticationProvider(`${userGroup2Id}/${user2Id}`, userPw12), fetch).getCurrentUser()\n await new IccUserApi(env.iCureUrl, {}, new BasicAuthenticationProvider(`${userGroup3Id}/${user3Id}`, userPw3), fetch).getCurrentUser()\n },\n 10,\n 5_000,\n 1\n )\n return {\n user1,\n user2,\n user3,\n group1,\n group2,\n group3,\n userPw12,\n userPw3,\n userLogin,\n }\n}\n\nexport function isLiteTest() {\n return getEnvVariables().testEnvironment == 'oss'\n}\n\nexport function describeNoLite(title: string, fn: (this: Suite) => void): Suite | void {\n if (isLiteTest()) {\n return describe.skip(title, fn)\n } else {\n return describe(title, fn)\n }\n}\n\nexport function itNoLite(title: string, fn: (this: Context) => PromiseLike<any>): Test {\n if (isLiteTest()) {\n return it.skip(title, fn)\n } else {\n return it(title, fn)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"test_utils.js","sourceRoot":"","sources":["../../../test/utils/test_utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,+CAWwB;AACxB,2BAA2B;AAC3B,+BAA+C;AAC/C,+BAAiC;AACjC,mCAAkC;AAClC,uCAAmC;AACnC,oCAAqD;AACrD,+CAAmD;AACnD,iEAA6D;AAC7D,mDAA+C;AAC/C,uDAAkE;AAClE,mDAAgF;AAEhF,4BAAyB;AACzB,yDAA8D;AAC9D,2CAA0C;AAC1C,iCAAsD;AAGtD,SAAgB,YAAY;IAC1B,OAAO,GAAG,IAAA,SAAI,GAAE,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,YAAY,CAAA;AAC9C,CAAC;AAFD,oCAEC;AAED,SAAgB,eAAe,CAAC,KAAoE;IAClG,CAAC;IAAC,MAAc,CAAC,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,YAAY,CAAC,CAAC,IAAA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AAI,uCAA2B,CAAC,GAAG,YAAY,IAAI,OAAO,EAAE,EAAE,QAAQ,CAAC,EAAE,KAAK,CAAC,CAAC,cAAc,EAAE,CAAA;YACvI,MAAM,IAAI,oBAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,EAAE,IAAI,uCAA2B,CAAC,GAAG,YAAY,IAAI,OAAO,EAAE,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC,cAAc,EAAE,CAAA;QACxI,CAAC,CAAA,EACD,EAAE,EACF,IAAK,EACL,CAAC,CACF,CAAA;QACD,OAAO;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,MAAM;YACN,MAAM;YACN,MAAM;YACN,QAAQ;YACR,OAAO;YACP,SAAS;SACV,CAAA;IACH,CAAC;CAAA;AAxFD,gEAwFC;AAED,SAAgB,UAAU;IACxB,OAAO,IAAA,uBAAe,GAAE,CAAC,eAAe,IAAI,KAAK,CAAA;AACnD,CAAC;AAFD,gCAEC;AAED,SAAgB,cAAc,CAAC,KAAa,EAAE,EAAyB;IACrE,IAAI,UAAU,EAAE,EAAE;QAChB,OAAO,gBAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;KAChC;SAAM;QACL,OAAO,IAAA,gBAAQ,EAAC,KAAK,EAAE,EAAE,CAAC,CAAA;KAC3B;AACH,CAAC;AAND,wCAMC;AAED,SAAgB,QAAQ,CAAC,KAAa,EAAE,EAAuC;IAC7E,IAAI,UAAU,EAAE,EAAE;QAChB,OAAO,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;KAC1B;SAAM;QACL,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;KACrB;AACH,CAAC;AAND,4BAMC","sourcesContent":["import {\n BasicApis,\n BasicAuthenticationProvider,\n CryptoPrimitives,\n hex2ua,\n IcureApi,\n IcureApiOptions,\n retry,\n RSAUtils,\n ShaVersion,\n ua2hex,\n} from '../../icc-x-api'\nimport { tmpdir } from 'os'\nimport { TextDecoder, TextEncoder } from 'util'\nimport { v4 as uuid } from 'uuid'\nimport { webcrypto } from 'crypto'\nimport { TestApi } from './TestApi'\nimport { IcureApi as TestSetupApi } from '@icure/api'\nimport { testStorageWithKeys } from './TestStorage'\nimport { TestCryptoStrategies } from './TestCryptoStrategies'\nimport { User } from '../../icc-api/model/User'\nimport { TestEnvironmentBuilder } from '@icure/test-setup/builder'\nimport { getEnvVariables, TestVars, UserDetails } from '@icure/test-setup/types'\nimport { EnvInitializer } from '@icure/test-setup/decorators'\nimport 'isomorphic-fetch'\nimport { createPatientUser } from '@icure/test-setup/creation'\nimport { IccUserApi } from '../../icc-api'\nimport { Context, describe, Suite, Test } from 'mocha'\nimport { Group } from '../../icc-api/model/Group'\n\nexport function getTempEmail(): string {\n return `${uuid().substring(0, 8)}@icure.com`\n}\n\nexport function setLocalStorage(fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>) {\n ;(global as any).localStorage = new (require('node-localstorage').LocalStorage)(tmpdir(), 5 * 1024 ** 3)\n ;(global as any).fetch = fetch\n ;(global as any).Storage = ''\n ;(global as any).TextDecoder = TextDecoder\n ;(global as any).TextEncoder = TextEncoder\n ;(global as any).headers = Headers\n}\n\nexport const hcp1Username = process.env.ICURE_TS_TEST_HCP_USER ?? getTempEmail()\nexport const hcp2Username = process.env.ICURE_TS_TEST_HCP_2_USER ?? getTempEmail()\nexport const hcp3Username = process.env.ICURE_TS_TEST_HCP_3_USER ?? getTempEmail()\nexport const patUsername = process.env.ICURE_TS_TEST_PAT_USER ?? getTempEmail()\n\nexport const deviceUsername = getTempEmail()\n\nlet cachedInitializer: EnvInitializer | undefined\n\nexport async function getEnvironmentInitializer(): Promise<EnvInitializer> {\n if (!cachedInitializer) {\n const env = getEnvVariables()\n const scratchDir = 'test/scratch'\n const baseEnvironment =\n env.testEnvironment === 'docker' || env.testEnvironment === 'oss'\n ? new TestEnvironmentBuilder().setUpDockerEnvironment(scratchDir, ['mock'])\n : new TestEnvironmentBuilder()\n cachedInitializer = await baseEnvironment\n .withGroup(fetch, {\n patient: ['BASIC_USER', 'BASIC_DATA_OWNER'],\n hcp: [\n 'BASIC_USER',\n 'BASIC_DATA_OWNER',\n 'PATIENT_USER_MANAGER',\n 'HIERARCHICAL_DATA_OWNER',\n 'TOPIC_MANAGER',\n 'TOPIC_PARTICIPANT',\n 'LEGACY_MESSAGE_MANAGER',\n ],\n device: ['BASIC_USER', 'BASIC_DATA_OWNER'],\n user: ['BASIC_USER'],\n })\n .withMasterUser(fetch)\n .addHcp({ login: hcp1Username })\n .addHcp({ login: hcp2Username })\n .addHcp({ login: hcp3Username })\n .addPatient({ login: patUsername })\n .addDevice({ login: deviceUsername })\n .withSafeguard()\n .withEnvironmentSummary()\n .build()\n }\n return cachedInitializer\n}\n\nexport namespace TestUtils {\n export async function initApi(envVars: TestVars, userName: string = hcp1Username, options?: IcureApiOptions): Promise<IcureApi> {\n return await getApiAndAddPrivateKeysForUser(envVars.iCureUrl, envVars.dataOwnerDetails[userName], options)\n }\n\n export async function initMasterApi(envVars: TestVars, options?: IcureApiOptions): Promise<IcureApi> {\n return await getApiAndAddPrivateKeysForUser(envVars.iCureUrl, envVars.masterHcp!, options)\n }\n}\n\nexport async function getApiAndAddPrivateKeysForUser(iCureUrl: string, details: UserDetails, options?: IcureApiOptions) {\n const RSA = new RSAUtils(webcrypto as any)\n const keys = {\n publicKey: await RSA.importKey('spki', hex2ua(details.publicKey), ['encrypt'], ShaVersion.Sha1),\n privateKey: await RSA.importKey('pkcs8', hex2ua(details.privateKey), ['decrypt'], ShaVersion.Sha1),\n }\n return await TestApi(iCureUrl, details.user, details.password, webcrypto as any, keys, options)\n}\n\nasync function createHealthcarePartyUser(\n api: TestSetupApi,\n userLogin: string,\n userToken: string,\n publicKey?: string,\n privateKey?: string\n): Promise<UserDetails> {\n const { publicKey: newPublicKey, privateKey: newPrivateKey } = await api.cryptoApi.RSA.generateKeyPair()\n\n const publicKeyHex = !!publicKey && !!privateKey ? publicKey : ua2hex(await api.cryptoApi.RSA.exportKey(newPublicKey, 'spki'))\n const privateKeyHex = !!publicKey && !!privateKey ? privateKey : ua2hex(await api.cryptoApi.RSA.exportKey(newPrivateKey, 'pkcs8'))\n\n const hcp = await api.healthcarePartyApi.createHealthcareParty({\n id: uuid(),\n firstName: uuid().substring(0, 6),\n lastName: uuid().substring(0, 6),\n publicKey: publicKeyHex,\n })\n const hcpUser = await api.userApi.createUser(\n new User({\n id: uuid(),\n name: userLogin,\n login: userLogin,\n email: userLogin,\n healthcarePartyId: hcp.id,\n })\n )\n const token = await api.userApi.getToken(hcpUser.id!, uuid(), 24 * 60 * 60, userToken)\n return {\n user: hcpUser.login!,\n dataOwnerId: hcp.id!,\n password: token,\n publicKey: publicKeyHex,\n privateKey: privateKeyHex,\n }\n}\n\nexport async function createNewHcpApi(env: TestVars): Promise<{\n api: IcureApi\n credentials: UserDetails\n user: User\n}> {\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const credentials = await createHealthcarePartyUser(initialisationApi, `user-${primitives.randomUuid()}`, primitives.randomUuid())\n const storage = await testStorageWithKeys([\n {\n dataOwnerId: credentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: credentials.privateKey, publicKey: credentials.publicKey }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const api = await IcureApi.initialise(\n env.iCureUrl,\n { username: credentials.user, password: credentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: storage.storage,\n keyStorage: storage.keyStorage,\n entryKeysFactory: storage.keyFactory,\n }\n )\n return { api, credentials, user: await api.userApi.getCurrentUser() }\n}\n\nexport async function createNewPatientApi(env: TestVars): Promise<{\n api: IcureApi\n credentials: UserDetails\n user: User\n}> {\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const credentials = await createPatientUser(initialisationApi, `user-${primitives.randomUuid()}`, primitives.randomUuid())\n const storage = await testStorageWithKeys([\n {\n dataOwnerId: credentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: credentials.privateKey, publicKey: credentials.publicKey }, shaVersion: ShaVersion.Sha1 }],\n },\n ])\n const api = await IcureApi.initialise(\n env.iCureUrl,\n { username: credentials.user, password: credentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: storage.storage,\n keyStorage: storage.keyStorage,\n entryKeysFactory: storage.keyFactory,\n }\n )\n return { api, credentials, user: await api.userApi.getCurrentUser() }\n}\n\n/**\n * Creates a hierarchy of HCPs with the following structure:\n * grand HCP -+-> parent HCP ---> child HCP\n * |\n * +-> child2 HCP\n */\nexport async function createHcpHierarchyApis(\n env: TestVars,\n setupAutodelegations: boolean = true,\n disableParentKeysInitialisation: boolean = false\n): Promise<{\n grandApi: IcureApi\n grandUser: User\n grandCredentials: UserDetails\n parentApi: IcureApi\n parentUser: User\n parentCredentials: UserDetails\n childApi: IcureApi\n childUser: User\n childCredentials: UserDetails\n child2Api: IcureApi\n child2User: User\n child2Credentials: UserDetails\n}> {\n const shaVersion = ShaVersion.Sha1\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const grandCredentials = await createHealthcarePartyUser(initialisationApi, `grand-${primitives.randomUuid()}`, primitives.randomUuid())\n const parentCredentials = await createHealthcarePartyUser(initialisationApi, `parent-${primitives.randomUuid()}`, primitives.randomUuid())\n const childCredentials = await createHealthcarePartyUser(initialisationApi, `child-${primitives.randomUuid()}`, primitives.randomUuid())\n const child2Credentials = await createHealthcarePartyUser(initialisationApi, `child2-${primitives.randomUuid()}`, primitives.randomUuid())\n await initialisationApi.healthcarePartyApi.modifyHealthcareParty({\n ...(await initialisationApi.healthcarePartyApi.getHealthcareParty(parentCredentials.dataOwnerId)),\n parentId: grandCredentials.dataOwnerId,\n })\n await initialisationApi.healthcarePartyApi.modifyHealthcareParty({\n ...(await initialisationApi.healthcarePartyApi.getHealthcareParty(childCredentials.dataOwnerId)),\n parentId: parentCredentials.dataOwnerId,\n })\n await initialisationApi.healthcarePartyApi.modifyHealthcareParty({\n ...(await initialisationApi.healthcarePartyApi.getHealthcareParty(child2Credentials.dataOwnerId)),\n parentId: grandCredentials.dataOwnerId,\n })\n const grandStorage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const grandApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: grandCredentials.user, password: grandCredentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: grandStorage.storage,\n keyStorage: grandStorage.keyStorage,\n entryKeysFactory: grandStorage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const parentStorage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: parentCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: parentCredentials.privateKey, publicKey: parentCredentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const parentApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: parentCredentials.user, password: parentCredentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: parentStorage.storage,\n keyStorage: parentStorage.keyStorage,\n entryKeysFactory: parentStorage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const parentUser = setupAutodelegations\n ? await parentApi.userApi.modifyUser({\n ...(await parentApi.userApi.getCurrentUser()),\n autoDelegations: { all: [grandCredentials.dataOwnerId] },\n })\n : await parentApi.userApi.getCurrentUser()\n const childStorage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: parentCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: parentCredentials.privateKey, publicKey: parentCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: childCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: childCredentials.privateKey, publicKey: childCredentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const childApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: childCredentials.user, password: childCredentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: childStorage.storage,\n keyStorage: childStorage.keyStorage,\n entryKeysFactory: childStorage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const childUser = setupAutodelegations\n ? await childApi.userApi.modifyUser({\n ...(await childApi.userApi.getCurrentUser()),\n autoDelegations: { all: [grandCredentials.dataOwnerId, parentCredentials.dataOwnerId] },\n })\n : await childApi.userApi.getCurrentUser()\n const child2Storage = await testStorageWithKeys([\n {\n dataOwnerId: grandCredentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: grandCredentials.privateKey, publicKey: grandCredentials.publicKey }, shaVersion: shaVersion }],\n },\n {\n dataOwnerId: child2Credentials.dataOwnerId,\n pairs: [{ keyPair: { privateKey: child2Credentials.privateKey, publicKey: child2Credentials.publicKey }, shaVersion: shaVersion }],\n },\n ])\n const child2Api = await IcureApi.initialise(\n env.iCureUrl,\n { username: child2Credentials.user, password: child2Credentials.password },\n new TestCryptoStrategies(),\n webcrypto as any,\n fetch,\n {\n storage: child2Storage.storage,\n keyStorage: child2Storage.keyStorage,\n entryKeysFactory: child2Storage.keyFactory,\n disableParentKeysInitialisation,\n }\n )\n const child2User = setupAutodelegations\n ? await child2Api.userApi.modifyUser({\n ...(await child2Api.userApi.getCurrentUser()),\n autoDelegations: { all: [grandCredentials.dataOwnerId] },\n })\n : await child2Api.userApi.getCurrentUser()\n return {\n grandApi,\n grandUser: await grandApi.userApi.getCurrentUser(),\n grandCredentials,\n parentApi,\n parentUser,\n parentCredentials,\n childApi,\n childUser,\n childCredentials,\n child2Api,\n child2User,\n child2Credentials,\n }\n}\n\n/**\n * Create a parent HCP with a key and a child HCP without any initialised key\n */\nexport async function createNewHcpWithoutKeyAndParentWithKey(\n env: TestVars,\n props: {\n initialiseEmptyKeyForChild?: boolean\n } = {}\n): Promise<{\n parentCredentials: UserDetails\n childUser: string\n childDataOwnerId: string\n childPassword: string\n}> {\n const initialisationApi = await testSetupMasterApi(env)\n const primitives = new CryptoPrimitives(webcrypto as any)\n const parentCredentials = await createHealthcarePartyUser(initialisationApi, `parent-${primitives.randomUuid()}`, primitives.randomUuid())\n const childUser = uuid() + '@email.com'\n const childPassword = uuid()\n const childHcp = {\n id: uuid(),\n firstName: uuid().substring(0, 6),\n lastName: uuid().substring(0, 6),\n parentId: parentCredentials.dataOwnerId,\n publicKey: undefined as string | undefined,\n }\n if (props.initialiseEmptyKeyForChild) {\n childHcp.publicKey = ''\n }\n await initialisationApi.healthcarePartyApi.createHealthcareParty(childHcp)\n await initialisationApi.userApi.createUser(\n new User({\n id: uuid(),\n name: childUser,\n login: childUser,\n email: childUser,\n passwordHash: childPassword,\n healthcarePartyId: childHcp.id,\n })\n )\n return {\n parentCredentials,\n childUser,\n childPassword,\n childDataOwnerId: childHcp.id!,\n }\n}\n\nexport function testSetupMasterApi(env: TestVars): Promise<TestSetupApi> {\n return TestSetupApi.initialise(\n env.iCureUrl,\n { username: env.masterHcp!.user, password: env.masterHcp!.password },\n {\n generateNewKeyForDataOwner(): Promise<boolean> {\n return Promise.resolve(true)\n },\n recoverAndVerifySelfHierarchyKeys(): never {\n throw new Error('Unsupported')\n },\n verifyDelegatePublicKeys(delegate: any, publicKeys: string[]): Promise<string[]> {\n return Promise.resolve(publicKeys)\n },\n },\n webcrypto as any,\n fetch\n )\n}\n\nexport type UserInManyGroupsDetails = {\n user1: User\n user2: User\n group3: Group\n userPw3: string\n user3: User\n group2: Group\n group1: Group\n userPw12: string\n userLogin: string\n}\nexport async function createUserInMultipleGroups(env: TestVars): Promise<UserInManyGroupsDetails> {\n const primitives = new CryptoPrimitives(webcrypto as any)\n const userGroup1Id: string = primitives.randomUuid() // Same username-pw as group 2\n const userGroup2Id: string = primitives.randomUuid() // Same username-pw as group 1\n const userGroup3Id: string = primitives.randomUuid() // Same username as group 1/2, different pw\n const userLogin: string = `maria-${primitives.randomUuid()}@pompei.it`\n const userPw12: string = `geppetto-${primitives.randomUuid()}`\n const userPw3: string = `pinocchio-${primitives.randomUuid()}`\n const user1Id: string = primitives.randomUuid()\n const user2Id: string = primitives.randomUuid()\n const user3Id: string = primitives.randomUuid()\n const api = await BasicApis(env.iCureUrl, { username: 'john', password: 'LetMeIn' }, webcrypto as any, fetch) // pragma: allowlist secret\n const group1 = await api.groupApi.createGroup(\n userGroup1Id,\n `test-group-1-${primitives.randomUuid()}`,\n primitives.randomUuid(),\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n {}\n )\n const group2 = await api.groupApi.createGroup(\n userGroup2Id,\n `test-group-2-${primitives.randomUuid()}`,\n primitives.randomUuid(),\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n {}\n )\n const group3 = await api.groupApi.createGroup(\n userGroup3Id,\n `test-group-3-${primitives.randomUuid()}`,\n primitives.randomUuid(),\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n {}\n )\n const user1 = await api.userApi.createUserInGroup(userGroup1Id, {\n id: user1Id,\n name: userLogin,\n login: userLogin,\n email: userLogin,\n passwordHash: userPw12,\n })\n const user2 = await api.userApi.createUserInGroup(userGroup2Id, {\n id: user2Id,\n name: userLogin,\n login: userLogin,\n email: userLogin,\n passwordHash: userPw12,\n })\n const user3 = await api.userApi.createUserInGroup(userGroup3Id, {\n id: user3Id,\n name: userLogin,\n login: userLogin,\n email: userLogin,\n passwordHash: userPw3,\n })\n console.log(`Waiting for user to be created - ${userLogin}`)\n await retry(\n async () => {\n await new IccUserApi(env.iCureUrl, {}, new BasicAuthenticationProvider(`${userGroup1Id}/${user1Id}`, userPw12), fetch).getCurrentUser()\n await new IccUserApi(env.iCureUrl, {}, new BasicAuthenticationProvider(`${userGroup2Id}/${user2Id}`, userPw12), fetch).getCurrentUser()\n await new IccUserApi(env.iCureUrl, {}, new BasicAuthenticationProvider(`${userGroup3Id}/${user3Id}`, userPw3), fetch).getCurrentUser()\n },\n 10,\n 5_000,\n 1\n )\n return {\n user1,\n user2,\n user3,\n group1,\n group2,\n group3,\n userPw12,\n userPw3,\n userLogin,\n }\n}\n\nexport function isLiteTest() {\n return getEnvVariables().testEnvironment == 'oss'\n}\n\nexport function describeNoLite(title: string, fn: (this: Suite) => void): Suite | void {\n if (isLiteTest()) {\n return describe.skip(title, fn)\n } else {\n return describe(title, fn)\n }\n}\n\nexport function itNoLite(title: string, fn: (this: Context) => PromiseLike<any>): Test {\n if (isLiteTest()) {\n return it.skip(title, fn)\n } else {\n return it(title, fn)\n }\n}\n"]}
|