From 996808ebd83a1cc27a5e277f003ee8bdef6b0b7e Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Tue, 12 Mar 2024 17:58:56 +0530 Subject: [PATCH 01/11] refactor: agent token encryption Signed-off-by: KulkarniShashank --- .../src/agent-service.controller.ts | 81 ++++----- .../src/agent-service.service.ts | 170 +++++++++++------- .../src/interface/agent-service.interface.ts | 4 + apps/connection/src/connection.service.ts | 74 +++----- apps/ecosystem/src/ecosystem.service.ts | 36 ++-- .../interfaces/issuance.interfaces.ts | 5 +- apps/issuance/src/issuance.service.ts | 49 ++--- .../credential-definition.service.ts | 20 +-- .../credential-definition.interface.ts | 2 + apps/ledger/src/schema/schema.interface.ts | 2 + apps/ledger/src/schema/schema.service.ts | 20 +-- .../src/interfaces/verification.interface.ts | 15 +- apps/verification/src/verification.service.ts | 42 ++--- 13 files changed, 236 insertions(+), 284 deletions(-) diff --git a/apps/agent-service/src/agent-service.controller.ts b/apps/agent-service/src/agent-service.controller.ts index 163c7edca..8046c80a9 100644 --- a/apps/agent-service/src/agent-service.controller.ts +++ b/apps/agent-service/src/agent-service.controller.ts @@ -54,17 +54,17 @@ export class AgentServiceController { //DONE @MessagePattern({ cmd: 'agent-create-connection-legacy-invitation' }) - async createLegacyConnectionInvitation(payload: { connectionPayload: IConnectionDetails, url: string, apiKey: string }): Promise { - return this.agentServiceService.createLegacyConnectionInvitation(payload.connectionPayload, payload.url, payload.apiKey); + async createLegacyConnectionInvitation(payload: { connectionPayload: IConnectionDetails, url: string, orgId: string }): Promise { + return this.agentServiceService.createLegacyConnectionInvitation(payload.connectionPayload, payload.url, payload.orgId); } @MessagePattern({ cmd: 'agent-send-credential-create-offer' }) async sendCredentialCreateOffer(payload: { issueData: IIssuanceCreateOffer; url: string; - apiKey: string; + orgId: string; }): Promise { - return this.agentServiceService.sendCredentialCreateOffer(payload.issueData, payload.url, payload.apiKey); + return this.agentServiceService.sendCredentialCreateOffer(payload.issueData, payload.url, payload.orgId); } //DONE @@ -75,8 +75,8 @@ export class AgentServiceController { //DONE @MessagePattern({ cmd: 'agent-get-issued-credentials-by-credentialDefinitionId' }) - async getIssueCredentialsbyCredentialRecordId(payload: { url: string; apiKey: string }): Promise { - return this.agentServiceService.getIssueCredentialsbyCredentialRecordId(payload.url, payload.apiKey); + async getIssueCredentialsbyCredentialRecordId(payload: { url: string; orgId: string }): Promise { + return this.agentServiceService.getIssueCredentialsbyCredentialRecordId(payload.url, payload.orgId); } //DONE @MessagePattern({ cmd: 'agent-get-proof-presentations' }) @@ -86,8 +86,8 @@ export class AgentServiceController { //DONE @MessagePattern({ cmd: 'agent-get-proof-presentation-by-id' }) - async getProofPresentationById(payload: { url: string; apiKey: string }): Promise { - return this.agentServiceService.getProofPresentationById(payload.url, payload.apiKey); + async getProofPresentationById(payload: { url: string; orgId: string }): Promise { + return this.agentServiceService.getProofPresentationById(payload.url, payload.orgId); } //DONE @@ -95,25 +95,25 @@ export class AgentServiceController { async sendProofRequest(payload: { proofRequestPayload: ISendProofRequestPayload; url: string; - apiKey: string; + orgId: string; }): Promise { - return this.agentServiceService.sendProofRequest(payload.proofRequestPayload, payload.url, payload.apiKey); + return this.agentServiceService.sendProofRequest(payload.proofRequestPayload, payload.url, payload.orgId); } //DONE @MessagePattern({ cmd: 'agent-verify-presentation' }) - async verifyPresentation(payload: { url: string; apiKey: string }): Promise { - return this.agentServiceService.verifyPresentation(payload.url, payload.apiKey); + async verifyPresentation(payload: { url: string; orgId: string }): Promise { + return this.agentServiceService.verifyPresentation(payload.url, payload.orgId); } //DONE @MessagePattern({ cmd: 'agent-get-all-connections' }) - async getConnections(payload: { url: string; apiKey: string }): Promise { - return this.agentServiceService.getConnections(payload.url, payload.apiKey); + async getConnections(payload: { url: string; orgId: string }): Promise { + return this.agentServiceService.getConnections(payload.url, payload.orgId); } @MessagePattern({ cmd: 'agent-get-connection-details-by-connectionId' }) - async getConnectionsByconnectionId(payload: { url: string, apiKey: string }): Promise { - return this.agentServiceService.getConnectionsByconnectionId(payload.url, payload.apiKey); + async getConnectionsByconnectionId(payload: { url: string, orgId: string }): Promise { + return this.agentServiceService.getConnectionsByconnectionId(payload.url, payload.orgId); } /** @@ -131,54 +131,54 @@ export class AgentServiceController { async sendOutOfBandProofRequest(payload: { proofRequestPayload: ISendProofRequestPayload; url: string; - apiKey: string; + orgId: string; }): Promise { - return this.agentServiceService.sendOutOfBandProofRequest(payload.proofRequestPayload, payload.url, payload.apiKey); + return this.agentServiceService.sendOutOfBandProofRequest(payload.proofRequestPayload, payload.url, payload.orgId); } //DONE @MessagePattern({ cmd: 'get-agent-verified-proof-details' }) - async getVerifiedProofDetails(payload: { url: string; apiKey: string }): Promise { - return this.agentServiceService.getVerifiedProofDetails(payload.url, payload.apiKey); + async getVerifiedProofDetails(payload: { url: string; orgId: string }): Promise { + return this.agentServiceService.getVerifiedProofDetails(payload.url, payload.orgId); } @MessagePattern({ cmd: 'agent-schema-endorsement-request' }) async schemaEndorsementRequest(payload: { url: string; - apiKey: string; + orgId: string; requestSchemaPayload: object; }): Promise { - return this.agentServiceService.schemaEndorsementRequest(payload.url, payload.apiKey, payload.requestSchemaPayload); + return this.agentServiceService.schemaEndorsementRequest(payload.url, payload.orgId, payload.requestSchemaPayload); } @MessagePattern({ cmd: 'agent-credDef-endorsement-request' }) async credDefEndorsementRequest(payload: { url: string; - apiKey: string; + orgId: string; requestSchemaPayload: object; }): Promise { return this.agentServiceService.credDefEndorsementRequest( payload.url, - payload.apiKey, + payload.orgId, payload.requestSchemaPayload ); } //DONE @MessagePattern({ cmd: 'agent-sign-transaction' }) - async signTransaction(payload: { url: string; apiKey: string; signEndorsementPayload: object }): Promise { - return this.agentServiceService.signTransaction(payload.url, payload.apiKey, payload.signEndorsementPayload); + async signTransaction(payload: { url: string; orgId: string; signEndorsementPayload: object }): Promise { + return this.agentServiceService.signTransaction(payload.url, payload.orgId, payload.signEndorsementPayload); } //DONE @MessagePattern({ cmd: 'agent-submit-transaction' }) - async submitTransaction(payload: { url: string; apiKey: string; submitEndorsementPayload: object }): Promise { - return this.agentServiceService.sumbitTransaction(payload.url, payload.apiKey, payload.submitEndorsementPayload); + async submitTransaction(payload: { url: string; orgId: string; submitEndorsementPayload: object }): Promise { + return this.agentServiceService.sumbitTransaction(payload.url, payload.orgId, payload.submitEndorsementPayload); } //DONE @MessagePattern({ cmd: 'agent-out-of-band-credential-offer' }) - async outOfBandCredentialOffer(payload: { outOfBandIssuancePayload: IOutOfBandCredentialOffer, url: string, apiKey: string }): Promise { - return this.agentServiceService.outOfBandCredentialOffer(payload.outOfBandIssuancePayload, payload.url, payload.apiKey); + async outOfBandCredentialOffer(payload: { outOfBandIssuancePayload: IOutOfBandCredentialOffer, url: string, orgId: string }): Promise { + return this.agentServiceService.outOfBandCredentialOffer(payload.outOfBandIssuancePayload, payload.url, payload.orgId); } @MessagePattern({ cmd: 'delete-wallet' }) @@ -186,42 +186,37 @@ export class AgentServiceController { return this.agentServiceService.deleteWallet(payload.url, payload.apiKey); } - @MessagePattern({ cmd: 'get-org-agent-api-key' }) - async getOrgAgentApiKey(payload: { orgId: string }): Promise { - return this.agentServiceService.getOrgAgentApiKey(payload.orgId); - } - @MessagePattern({ cmd: 'agent-receive-invitation-url' }) async receiveInvitationUrl(payload: { url, - apiKey, + orgId, receiveInvitationUrl }): Promise { - return this.agentServiceService.receiveInvitationUrl(payload.receiveInvitationUrl, payload.url, payload.apiKey); + return this.agentServiceService.receiveInvitationUrl(payload.receiveInvitationUrl, payload.url, payload.orgId); } @MessagePattern({ cmd: 'agent-receive-invitation' }) async receiveInvitation(payload: { url, - apiKey, + orgId, receiveInvitation }): Promise { - return this.agentServiceService.receiveInvitation(payload.receiveInvitation, payload.url, payload.apiKey); + return this.agentServiceService.receiveInvitation(payload.receiveInvitation, payload.url, payload.orgId); } @MessagePattern({ cmd: 'agent-send-question' }) async sendQuestion(payload: { url, - apiKey, + orgId, questionPayload }): Promise { - return this.agentServiceService.sendQuestion(payload.questionPayload, payload.url, payload.apiKey); + return this.agentServiceService.sendQuestion(payload.questionPayload, payload.url, payload.orgId); } @MessagePattern({ cmd: 'agent-get-question-answer-record' }) - async getQuestionAnswersRecord(payload: { url: string, apiKey: string }): Promise { - return this.agentServiceService.getQuestionAnswersRecord(payload.url, payload.apiKey); + async getQuestionAnswersRecord(payload: { url: string, orgId: string }): Promise { + return this.agentServiceService.getQuestionAnswersRecord(payload.url, payload.orgId); } } diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 36552d004..2186740f7 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -37,6 +37,7 @@ import { IProofPresentationDetails } from '@credebl/common/interfaces/verificati import { ICreateConnectionUrl } from '@credebl/common/interfaces/connection.interface'; import { IConnectionDetailsById } from 'apps/api-gateway/src/interfaces/IConnectionSearch.interface'; import { InvitationMessage } from '@credebl/common/interfaces/agent-service.interface'; +import * as CryptoJS from 'crypto-js'; @Injectable() @WebSocketGateway() @@ -168,7 +169,6 @@ export class AgentServiceService { // Create payload for the wallet create and store payload const walletProvisionPayload = await this.prepareWalletProvisionPayload(agentSpinupDto, externalIp, apiEndpoint, inboundEndpoint, ledgerDetails, orgData); - // Socket connection const socket: Socket = await this.initSocketConnection(`${process.env.SOCKET_HOST}`); this.emitAgentSpinupInitiatedEvent(agentSpinupDto, socket); @@ -365,10 +365,12 @@ export class AgentServiceService { socket.emit('invitation-url-creation-started', { clientId: agentSpinupDto.clientSocketId }); } + const encryptedToken = await this.tokenEncryption(agentDetails?.agentToken); + const agentPayload: IStoreOrgAgentDetails = { agentEndPoint, seed: agentSpinupDto.seed, - apiKey: agentDetails.agentToken, + apiKey: encryptedToken, agentsTypeId: agentSpinupDto?.agentType, orgId: orgData.id, walletName: agentSpinupDto.walletName, @@ -514,8 +516,9 @@ export class AgentServiceService { this.logger.error(`[_storeOrgAgentDetails] - Error in store agent details : ${JSON.stringify(error)}`); } - + async _retryAgentSpinup(agentUrl: string, apiKey: string, agentApiState: string, seed?: string, indyNamespace?: string, did?: string): Promise { + const getDcryptedToken = await this.commonService.decryptPassword(apiKey); const retryOptions = { retries: 10 }; @@ -523,9 +526,9 @@ export class AgentServiceService { try { return retry(async () => { if (agentApiState === 'write-did') { - return this.commonService.httpPost(agentUrl, { seed, method: indyNamespace, did }, { headers: { 'authorization': apiKey } }); + return this.commonService.httpPost(agentUrl, { seed, method: indyNamespace, did }, { headers: { 'authorization': getDcryptedToken } }); } else if (agentApiState === 'get-did-doc') { - return this.commonService.httpGet(agentUrl, { headers: { 'authorization': apiKey } }); + return this.commonService.httpGet(agentUrl, { headers: { 'authorization': getDcryptedToken } }); } }, retryOptions); } catch (error) { @@ -776,12 +779,12 @@ export class AgentServiceService { method: ledgerIds.indyNamespace }; - + const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); // Invoke an API request from the agent to create multi-tenant agent const tenantDetails = await this.commonService.httpPost( `${platformAdminSpinnedUp.org_agents[0].agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`, createTenantOptions, - { headers: { 'authorization': platformAdminSpinnedUp.org_agents[0].apiKey } } + { headers: { 'authorization': getDcryptedToken } } ); return tenantDetails; @@ -815,6 +818,7 @@ export class AgentServiceService { async createSchema(payload: ITenantSchema): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(payload.orgId); let schemaResponse; if (OrgAgentType.DEDICATED === payload.agentType) { @@ -826,7 +830,7 @@ export class AgentServiceService { name: payload.name, issuerId: payload.issuerId }; - schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': payload.apiKey } }) + schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': getApiKey } }) .then(async (schema) => { return schema; }) @@ -846,7 +850,7 @@ export class AgentServiceService { name: payload.payload.name, issuerId: payload.payload.issuerId }; - schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': payload.apiKey } }) + schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': getApiKey } }) .then(async (schema) => { return schema; }) @@ -868,6 +872,7 @@ export class AgentServiceService { try { let schemaResponse; + const getApiKey = await this.getOrgAgentApiKey(payload.orgId); if (OrgAgentType.DEDICATED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_SCHEMA_BY_ID.replace('#', `${payload.schemaId}`)}`; schemaResponse = await this.commonService.httpGet(url, payload.schemaId) @@ -878,7 +883,7 @@ export class AgentServiceService { } else if (OrgAgentType.SHARED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_SCHEMA}`.replace('@', `${payload.payload.schemaId}`).replace('#', `${payload.tenantId}`); - schemaResponse = await this.commonService.httpGet(url, { headers: { 'authorization': payload.apiKey } }) + schemaResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async (schema) => { return schema; }); @@ -894,6 +899,7 @@ export class AgentServiceService { try { let credDefResponse; + const getApiKey = await this.getOrgAgentApiKey(payload.orgId); if (OrgAgentType.DEDICATED === String(payload.agentType)) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_CREATE_CRED_DEF}`; @@ -903,7 +909,7 @@ export class AgentServiceService { issuerId: payload.issuerId }; - credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': payload.apiKey } }) + credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': getApiKey } }) .then(async (credDef) => { return credDef; }); @@ -915,7 +921,7 @@ export class AgentServiceService { schemaId: payload.payload.schemaId, issuerId: payload.payload.issuerId }; - credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': payload.apiKey } }) + credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': getApiKey } }) .then(async (credDef) => { return credDef; }); @@ -932,16 +938,17 @@ export class AgentServiceService { try { let credDefResponse; + const getApiKey = await this.getOrgAgentApiKey(payload.orgId); if (OrgAgentType.DEDICATED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_CRED_DEF_BY_ID.replace('#', `${payload.credentialDefinitionId}`)}`; - credDefResponse = await this.commonService.httpGet(url, payload.credentialDefinitionId) + credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async (credDef) => { return credDef; }); } else if (OrgAgentType.SHARED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CRED_DEF}`.replace('@', `${payload.payload.credentialDefinitionId}`).replace('#', `${payload.tenantId}`); - credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': payload.apiKey } }) + credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async (credDef) => { return credDef; }); @@ -953,12 +960,12 @@ export class AgentServiceService { } } - async createLegacyConnectionInvitation(connectionPayload: IConnectionDetails, url: string, apiKey: string): Promise { + async createLegacyConnectionInvitation(connectionPayload: IConnectionDetails, url: string, orgId: string): Promise { try { - + const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpPost(url, connectionPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, connectionPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return data; @@ -968,10 +975,11 @@ export class AgentServiceService { } } - async sendCredentialCreateOffer(issueData: IIssuanceCreateOffer, url: string, apiKey: string): Promise { + async sendCredentialCreateOffer(issueData: IIssuanceCreateOffer, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpPost(url, issueData, { headers: { 'authorization': apiKey } }) + .httpPost(url, issueData, { headers: { 'authorization': getApiKey } }) .then(async response => response); return data; } catch (error) { @@ -1004,10 +1012,11 @@ export class AgentServiceService { } } - async getProofPresentationById(url: string, apiKey: string): Promise { + async getProofPresentationById(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const getProofPresentationById = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) + .httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async response => response) .catch(error => this.handleAgentSpinupStatusErrors(error)); @@ -1018,10 +1027,11 @@ export class AgentServiceService { } } - async getIssueCredentialsbyCredentialRecordId(url: string, apiKey: string): Promise { + async getIssueCredentialsbyCredentialRecordId(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) + .httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async response => response); return data; } catch (error) { @@ -1030,10 +1040,11 @@ export class AgentServiceService { } } - async sendProofRequest(proofRequestPayload: ISendProofRequestPayload, url: string, apiKey: string): Promise { + async sendProofRequest(proofRequestPayload: ISendProofRequestPayload, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const sendProofRequest = await this.commonService - .httpPost(url, proofRequestPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, proofRequestPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return sendProofRequest; } catch (error) { @@ -1042,10 +1053,11 @@ export class AgentServiceService { } } - async verifyPresentation(url: string, apiKey: string): Promise { + async verifyPresentation(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const verifyPresentation = await this.commonService - .httpPost(url, '', { headers: { 'authorization': apiKey } }) + .httpPost(url, '', { headers: { 'authorization': getApiKey } }) .then(async response => response) .catch(error => this.handleAgentSpinupStatusErrors(error)); return verifyPresentation; @@ -1055,10 +1067,11 @@ export class AgentServiceService { } } - async getConnections(url: string, apiKey: string): Promise { + async getConnections(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) + .httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async response => response); return data; } catch (error) { @@ -1067,11 +1080,12 @@ export class AgentServiceService { } } - async getConnectionsByconnectionId(url: string, apiKey: string): Promise { + async getConnectionsByconnectionId(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) + .httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async response => response) .catch(error => this.handleAgentSpinupStatusErrors(error)); @@ -1096,15 +1110,7 @@ export class AgentServiceService { let agentApiKey; if (orgAgentDetails) { - - agentApiKey = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!agentApiKey || null === agentApiKey || undefined === agentApiKey) { - agentApiKey = await this.getOrgAgentApiKey(orgId); - } - - if (agentApiKey === undefined || null) { agentApiKey = await this.getOrgAgentApiKey(orgId); - } } if (!orgAgentDetails) { @@ -1134,10 +1140,11 @@ export class AgentServiceService { } } - async sendOutOfBandProofRequest(proofRequestPayload: ISendProofRequestPayload, url: string, apiKey: string): Promise { + async sendOutOfBandProofRequest(proofRequestPayload: ISendProofRequestPayload, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const sendProofRequest = await this.commonService - .httpPost(url, proofRequestPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, proofRequestPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return sendProofRequest; } catch (error) { @@ -1146,10 +1153,11 @@ export class AgentServiceService { } } - async getVerifiedProofDetails(url: string, apiKey: string): Promise { + async getVerifiedProofDetails(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const getVerifiedProofData = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) + .httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async response => response) .catch(error => this.handleAgentSpinupStatusErrors(error)); @@ -1160,10 +1168,11 @@ export class AgentServiceService { } } - async schemaEndorsementRequest(url: string, apiKey: string, requestSchemaPayload: object): Promise { + async schemaEndorsementRequest(url: string, orgId: string, requestSchemaPayload: object): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const schemaRequest = await this.commonService - .httpPost(url, requestSchemaPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, requestSchemaPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return schemaRequest; } catch (error) { @@ -1172,10 +1181,11 @@ export class AgentServiceService { } } - async credDefEndorsementRequest(url: string, apiKey: string, requestSchemaPayload: object): Promise { + async credDefEndorsementRequest(url: string, orgId: string, requestSchemaPayload: object): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const credDefRequest = await this.commonService - .httpPost(url, requestSchemaPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, requestSchemaPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return credDefRequest; } catch (error) { @@ -1184,10 +1194,11 @@ export class AgentServiceService { } } - async signTransaction(url: string, apiKey: string, signEndorsementPayload: object): Promise { + async signTransaction(url: string, orgId: string, signEndorsementPayload: object): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const signEndorsementTransaction = await this.commonService - .httpPost(url, signEndorsementPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, signEndorsementPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return signEndorsementTransaction; @@ -1197,11 +1208,11 @@ export class AgentServiceService { } } - async sumbitTransaction(url: string, apiKey: string, submitEndorsementPayload: object): Promise { + async sumbitTransaction(url: string, orgId: string, submitEndorsementPayload: object): Promise { try { - + const getApiKey = await this.getOrgAgentApiKey(orgId); const signEndorsementTransaction = await this.commonService - .httpPost(url, submitEndorsementPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, submitEndorsementPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return signEndorsementTransaction; @@ -1211,10 +1222,11 @@ export class AgentServiceService { } } - async outOfBandCredentialOffer(outOfBandIssuancePayload: IOutOfBandCredentialOffer, url: string, apiKey: string): Promise { + async outOfBandCredentialOffer(outOfBandIssuancePayload: IOutOfBandCredentialOffer, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const sendOutOfbandCredentialOffer = await this.commonService - .httpPost(url, outOfBandIssuancePayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, outOfBandIssuancePayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return sendOutOfbandCredentialOffer; } catch (error) { @@ -1238,10 +1250,11 @@ export class AgentServiceService { } } - async receiveInvitationUrl(receiveInvitationUrl: IReceiveInvitationUrl, url: string, apiKey: string): Promise { + async receiveInvitationUrl(receiveInvitationUrl: IReceiveInvitationUrl, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const receiveInvitationUrlRes = await this.commonService - .httpPost(url, receiveInvitationUrl, { headers: { 'authorization': apiKey } }) + .httpPost(url, receiveInvitationUrl, { headers: { 'authorization': getApiKey } }) .then(async response => response); return receiveInvitationUrlRes; } catch (error) { @@ -1250,10 +1263,11 @@ export class AgentServiceService { } } - async receiveInvitation(receiveInvitation: IReceiveInvitation, url: string, apiKey: string): Promise { + async receiveInvitation(receiveInvitation: IReceiveInvitation, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const receiveInvitationRes = await this.commonService - .httpPost(url, receiveInvitation, { headers: { 'authorization': apiKey } }) + .httpPost(url, receiveInvitation, { headers: { 'authorization': getApiKey } }) .then(async response => response); return receiveInvitationRes; } catch (error) { @@ -1262,16 +1276,22 @@ export class AgentServiceService { } } - async getOrgAgentApiKey(orgId: string): Promise { + private async getOrgAgentApiKey(orgId: string): Promise { try { let agentApiKey; const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); + const apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); + + if (apiKey) { + const getDcryptedToken = await this.commonService.decryptPassword(apiKey); + return getDcryptedToken; + } const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) { const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG); - + const [orgAgentData] = platformAdminSpinnedUp.org_agents; const { apiKey } = orgAgentData; if (!platformAdminSpinnedUp) { @@ -1287,8 +1307,11 @@ export class AgentServiceService { if (!agentApiKey) { throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); } + await this.cacheService.set(CommonConstants.CACHE_APIKEY_KEY, agentApiKey, CommonConstants.CACHE_TTL_SECONDS); - return agentApiKey; + const getDcryptedToken = await this.commonService.decryptPassword(agentApiKey); + + return getDcryptedToken; } catch (error) { this.logger.error(`Agent api key details : ${JSON.stringify(error)}`); @@ -1307,10 +1330,11 @@ export class AgentServiceService { } } - async sendQuestion(questionPayload: IQuestionPayload, url: string, apiKey: string): Promise { + async sendQuestion(questionPayload: IQuestionPayload, url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); const sendQuestionRes = await this.commonService - .httpPost(url, questionPayload, { headers: { 'authorization': apiKey } }) + .httpPost(url, questionPayload, { headers: { 'authorization': getApiKey } }) .then(async response => response); return sendQuestionRes; } catch (error) { @@ -1319,11 +1343,13 @@ export class AgentServiceService { } } - async getQuestionAnswersRecord(url: string, apiKey: string): Promise { + async getQuestionAnswersRecord(url: string, orgId: string): Promise { try { + const getApiKey = await this.getOrgAgentApiKey(orgId); + const data = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) + .httpGet(url, { headers: { 'authorization': getApiKey } }) .then(async response => response) .catch(error => this.handleAgentSpinupStatusErrors(error)); @@ -1335,5 +1361,19 @@ export class AgentServiceService { } + private async tokenEncryption(token: string): Promise { + try { + const encryptedToken = CryptoJS.AES.encrypt( + JSON.stringify(token), + process.env.CRYPTO_PRIVATE_KEY + ).toString(); + + return encryptedToken; + + } catch (error) { + throw error; + } + } + } diff --git a/apps/agent-service/src/interface/agent-service.interface.ts b/apps/agent-service/src/interface/agent-service.interface.ts index f52152eda..79a565979 100644 --- a/apps/agent-service/src/interface/agent-service.interface.ts +++ b/apps/agent-service/src/interface/agent-service.interface.ts @@ -53,6 +53,7 @@ export interface ITenantSchema { agentType?: string; apiKey?: string; agentEndPoint?: string; + orgId?: string; } export interface ITenantSchemaDto { @@ -70,6 +71,7 @@ export interface IGetSchemaAgentRedirection { agentEndPoint?: string; agentType?: string; method?: string; + orgId?: string; } export interface IGetSchemaFromTenantPayload { @@ -86,6 +88,7 @@ export interface ITenantCredDef { agentType?: string; apiKey?: string; agentEndPoint?: string; + orgId?: string; } export interface IWalletProvision { @@ -202,6 +205,7 @@ export interface IGetCredDefAgentRedirection { agentEndPoint?: string; agentType?: string; method?: string; + orgId?: string; } export interface IGetCredDefFromTenantPayload { diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index dc030a186..69823b1e5 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -77,12 +77,7 @@ export class ConnectionService { const orgAgentType = await this.connectionRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); const url = await this.getAgentUrl(orgAgentType, agentEndPoint, agentDetails?.tenantId); - - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const createConnectionInvitation = await this._createConnectionInvitation(connectionPayload, url, apiKey); + const createConnectionInvitation = await this._createConnectionInvitation(connectionPayload, url, orgId); const connectionInvitationUrl: string = createConnectionInvitation?.message?.invitationUrl; const shortenedUrl: string = await this.storeConnectionObjectAndReturnUrl( connectionInvitationUrl, @@ -146,11 +141,11 @@ export class ConnectionService { async _createConnectionInvitation( connectionPayload: object, url: string, - apiKey: string + orgId: string ): Promise { //nats call in agent-service to create an invitation url const pattern = { cmd: 'agent-create-connection-legacy-invitation' }; - const payload = { connectionPayload, url, apiKey }; + const payload = { connectionPayload, url, orgId }; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -286,12 +281,7 @@ export class ConnectionService { url += `?${criteriaParams.join('&')}`; } - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - - const connectionResponse = await this._getAllConnections(url, apiKey); + const connectionResponse = await this._getAllConnections(url, orgId); return connectionResponse.response; } catch (error) { this.logger.error(`[getConnectionsFromAgent] [NATS call]- error in fetch connections details : ${JSON.stringify(error)}`); @@ -302,13 +292,13 @@ export class ConnectionService { async _getAllConnections( url: string, - apiKey: string + orgId: string ): Promise<{ response: string; }> { try { const pattern = { cmd: 'agent-get-all-connections' }; - const payload = { url, apiKey }; + const payload = { url, orgId }; return this.connectionServiceProxy .send(pattern, payload) .pipe( @@ -357,12 +347,7 @@ export class ConnectionService { throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); } - // const apiKey = await this._getOrgAgentApiKey(orgId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const createConnectionInvitation = await this._getConnectionsByConnectionId(url, apiKey); + const createConnectionInvitation = await this._getConnectionsByConnectionId(url, orgId); return createConnectionInvitation; } catch (error) { this.logger.error(`[getConnectionsById] - error in get connections : ${JSON.stringify(error)}`); @@ -391,11 +376,7 @@ export class ConnectionService { const label = 'get-question-answer-record'; const url = await this.getQuestionAnswerAgentUrl(label, orgAgentType, agentEndPoint, agentDetails?.tenantId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const record = await this._getQuestionAnswersRecord(url, apiKey); + const record = await this._getQuestionAnswersRecord(url, orgId); return record; } catch (error) { this.logger.error(`[sendQuestion] - error in get question answer record: ${error}`); @@ -412,10 +393,10 @@ export class ConnectionService { } } - async _getConnectionsByConnectionId(url: string, apiKey: string): Promise { + async _getConnectionsByConnectionId(url: string, orgId: string): Promise { //nats call in agent service for fetch connection details const pattern = { cmd: 'agent-get-connection-details-by-connectionId' }; - const payload = { url, apiKey }; + const payload = { url, orgId }; return this.connectionServiceProxy .send(pattern, payload) .toPromise() @@ -434,9 +415,9 @@ export class ConnectionService { }); } - async _getQuestionAnswersRecord(url: string, apiKey: string): Promise { + async _getQuestionAnswersRecord(url: string, orgId: string): Promise { const pattern = { cmd: 'agent-get-question-answer-record' }; - const payload = { url, apiKey }; + const payload = { url, orgId }; return this.connectionServiceProxy .send(pattern, payload) .toPromise() @@ -572,11 +553,7 @@ export class ConnectionService { throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); } - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const createConnectionInvitation = await this._receiveInvitationUrl(url, apiKey, receiveInvitationUrl); + const createConnectionInvitation = await this._receiveInvitationUrl(url, orgId, receiveInvitationUrl); return createConnectionInvitation; } catch (error) { this.logger.error(`[receiveInvitationUrl] - error in receive invitation url : ${JSON.stringify(error)}`); @@ -595,11 +572,11 @@ export class ConnectionService { async _receiveInvitationUrl( url: string, - apiKey: string, + orgId: string, receiveInvitationUrl: IReceiveInvitationUrl ): Promise { const pattern = { cmd: 'agent-receive-invitation-url' }; - const payload = { url, apiKey, receiveInvitationUrl }; + const payload = { url, orgId, receiveInvitationUrl }; return this.connectionServiceProxy .send(pattern, payload) .toPromise() @@ -641,11 +618,7 @@ export class ConnectionService { throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); } - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const createConnectionInvitation = await this._receiveInvitation(url, apiKey, receiveInvitation); + const createConnectionInvitation = await this._receiveInvitation(url, orgId, receiveInvitation); return createConnectionInvitation; } catch (error) { this.logger.error(`[receiveInvitation] - error in receive invitation : ${JSON.stringify(error)}`); @@ -664,11 +637,11 @@ export class ConnectionService { async _receiveInvitation( url: string, - apiKey: string, + orgId: string, receiveInvitation: IReceiveInvitation ): Promise { const pattern = { cmd: 'agent-receive-invitation' }; - const payload = { url, apiKey, receiveInvitation }; + const payload = { url, orgId, receiveInvitation }; return this.connectionServiceProxy .send(pattern, payload) .toPromise() @@ -685,9 +658,9 @@ export class ConnectionService { }); } - async _sendQuestion(questionPayload: IQuestionPayload, url: string, apiKey: string): Promise { + async _sendQuestion(questionPayload: IQuestionPayload, url: string, orgId: string): Promise { const pattern = { cmd: 'agent-send-question' }; - const payload = { questionPayload, url, apiKey }; + const payload = { questionPayload, url, orgId }; return this.connectionServiceProxy .send(pattern, payload) @@ -731,11 +704,8 @@ export class ConnectionService { agentDetails?.tenantId, connectionId ); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const createQuestion = await this._sendQuestion(questionPayload, url, apiKey); + + const createQuestion = await this._sendQuestion(questionPayload, url, orgId); return createQuestion; } catch (error) { this.logger.error(`[sendQuestion] - error in sending question: ${error}`); diff --git a/apps/ecosystem/src/ecosystem.service.ts b/apps/ecosystem/src/ecosystem.service.ts index fa78b67c6..a67d4917e 100644 --- a/apps/ecosystem/src/ecosystem.service.ts +++ b/apps/ecosystem/src/ecosystem.service.ts @@ -754,7 +754,6 @@ export class EcosystemService { endorsementTransactionType.SCHEMA, ecosystemMemberDetails.tenantId ); - const apiKey = await this._getOrgAgentApiKey(orgId); const attributeArray = requestSchemaPayload.attributes.map((item) => item.attributeName); const schemaTransactionPayload = { @@ -769,7 +768,7 @@ export class EcosystemService { const schemaTransactionRequest: SchemaMessage = await this._requestSchemaEndorsement( schemaTransactionPayload, url, - apiKey + orgId ); const schemaTransactionResponse = { @@ -916,7 +915,6 @@ export class EcosystemService { endorsementTransactionType.CREDENTIAL_DEFINITION, ecosystemMemberDetails.tenantId ); - const apiKey = await this._getOrgAgentApiKey(orgId); const credDefTransactionPayload = { endorserDid: ecosystemLeadAgentDetails.orgDid, endorse: requestCredDefPayload.endorse, @@ -928,7 +926,7 @@ export class EcosystemService { const credDefTransactionRequest: CredDefMessage = await this._requestCredDeffEndorsement( credDefTransactionPayload, url, - apiKey + orgId ); if ('failed' === credDefTransactionRequest.message.credentialDefinitionState.state) { @@ -992,9 +990,9 @@ export class EcosystemService { } } - async _requestSchemaEndorsement(requestSchemaPayload: object, url: string, apiKey: string): Promise { + async _requestSchemaEndorsement(requestSchemaPayload: object, url: string, orgId: string): Promise { const pattern = { cmd: 'agent-schema-endorsement-request' }; - const payload = { requestSchemaPayload, url, apiKey }; + const payload = { requestSchemaPayload, url, orgId }; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -1012,9 +1010,9 @@ export class EcosystemService { } } - async _requestCredDeffEndorsement(requestSchemaPayload: object, url: string, apiKey: string): Promise { + async _requestCredDeffEndorsement(requestSchemaPayload: object, url: string, orgId: string): Promise { const pattern = { cmd: 'agent-credDef-endorsement-request' }; - const payload = { requestSchemaPayload, url, apiKey }; + const payload = { requestSchemaPayload, url, orgId }; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -1065,17 +1063,14 @@ export class EcosystemService { endorsementTransactionType.SIGN, ecosystemLeadAgentDetails?.tenantId ); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(ecosystemLeadDetails.orgId); - } + const jsonString = endorsementTransactionPayload.requestPayload.toString(); const payload = { transaction: jsonString, endorserDid: endorsementTransactionPayload.endorserDid }; - const schemaTransactionRequest: SignedTransactionMessage = await this._signTransaction(payload, url, apiKey); + const schemaTransactionRequest: SignedTransactionMessage = await this._signTransaction(payload, url, ecosystemLeadDetails.orgId); if (!schemaTransactionRequest) { throw new InternalServerErrorException(ResponseMessages.ecosystem.error.signRequestError); @@ -1180,9 +1175,9 @@ export class EcosystemService { * @param url * @returns sign message */ - async _signTransaction(signEndorsementPayload: object, url: string, apiKey: string): Promise { + async _signTransaction(signEndorsementPayload: object, url: string, orgId: string): Promise { const pattern = { cmd: 'agent-sign-transaction' }; - const payload = { signEndorsementPayload, url, apiKey }; + const payload = { signEndorsementPayload, url, orgId }; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -1369,12 +1364,7 @@ export class EcosystemService { } } - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - - const submitTransactionRequest = await this._submitTransaction(payload, url, apiKey); + const submitTransactionRequest = await this._submitTransaction(payload, url, orgId); if ('failed' === submitTransactionRequest['message'].state) { throw new InternalServerErrorException(ResponseMessages.ecosystem.error.sumbitTransaction); @@ -1448,9 +1438,9 @@ export class EcosystemService { * @param url * @returns sign message */ - async _submitTransaction(submitEndorsementPayload: object, url: string, apiKey: string): Promise { + async _submitTransaction(submitEndorsementPayload: object, url: string, orgId: string): Promise { const pattern = { cmd: 'agent-submit-transaction' }; - const payload = { submitEndorsementPayload, url, apiKey }; + const payload = { submitEndorsementPayload, url, orgId }; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/apps/issuance/interfaces/issuance.interfaces.ts b/apps/issuance/interfaces/issuance.interfaces.ts index 5cb4caa75..4bca2ffb7 100644 --- a/apps/issuance/interfaces/issuance.interfaces.ts +++ b/apps/issuance/interfaces/issuance.interfaces.ts @@ -85,7 +85,8 @@ export interface IPattern { export interface ISendOfferNatsPayload { issueData: IIssueData, url: string, - apiKey: string; + apiKey?: string; + orgId?: string; } export interface IIssueCredentialsDefinitions { @@ -254,6 +255,6 @@ export interface SendEmailCredentialOffer { organisation: organisation; errors; url: string; - apiKey: string; + orgId: string; organizationDetails: organisation; } \ No newline at end of file diff --git a/apps/issuance/src/issuance.service.ts b/apps/issuance/src/issuance.service.ts index a086d2bf5..9b27765d5 100644 --- a/apps/issuance/src/issuance.service.ts +++ b/apps/issuance/src/issuance.service.ts @@ -101,11 +101,6 @@ export class IssuanceService { const issuanceMethodLabel = 'create-offer'; const url = await this.getAgentUrl(issuanceMethodLabel, orgAgentType, agentEndPoint, agentDetails?.tenantId); - let apiKey; - apiKey = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } const issueData: IIssueData = { protocolVersion: 'v1', connectionId, @@ -121,7 +116,7 @@ export class IssuanceService { comment }; - const credentialCreateOfferDetails: ICreateOfferResponse = await this._sendCredentialCreateOffer(issueData, url, apiKey); + const credentialCreateOfferDetails: ICreateOfferResponse = await this._sendCredentialCreateOffer(issueData, url, orgId); if (credentialCreateOfferDetails && 0 < Object.keys(credentialCreateOfferDetails).length) { delete credentialCreateOfferDetails._tags; @@ -194,11 +189,7 @@ export class IssuanceService { const issuanceMethodLabel = 'create-offer-oob'; const url = await this.getAgentUrl(issuanceMethodLabel, orgAgentType, agentEndPoint, agentDetails?.tenantId); - let apiKey; - apiKey = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } + let issueData; if (credentialType === IssueCredentialType.INDY) { @@ -240,7 +231,7 @@ export class IssuanceService { comment: comment || '' }; } - const credentialCreateOfferDetails = await this._outOfBandCredentialOffer(issueData, url, apiKey); + const credentialCreateOfferDetails = await this._outOfBandCredentialOffer(issueData, url, orgId); if (isShortenUrl) { const invitationUrl: string = credentialCreateOfferDetails.response?.invitationUrl; const url: string = await this.storeIssuanceObjectReturnUrl(invitationUrl); @@ -326,10 +317,10 @@ export class IssuanceService { } } - async _sendCredentialCreateOffer(issueData: IIssueData, url: string, apiKey: string): Promise { + async _sendCredentialCreateOffer(issueData: IIssueData, url: string, orgId: string): Promise { try { const pattern = { cmd: 'agent-send-credential-create-offer' }; - const payload: ISendOfferNatsPayload = { issueData, url, apiKey }; + const payload: ISendOfferNatsPayload = { issueData, url, orgId }; return await this.natsCallAgent(pattern, payload); } catch (error) { this.logger.error(`[_sendCredentialCreateOffer] [NATS call]- error in create credentials : ${JSON.stringify(error)}`); @@ -398,13 +389,8 @@ export class IssuanceService { const issuanceMethodLabel = 'get-issue-credential-by-credential-id'; const url = await this.getAgentUrl(issuanceMethodLabel, orgAgentType, agentEndPoint, agentDetails?.tenantId, credentialRecordId); - // const apiKey = platformConfig?.sgApiKey; - // const apiKey = await this._getOrgAgentApiKey(orgId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const createConnectionInvitation = await this._getIssueCredentialsbyCredentialRecordId(url, apiKey); + + const createConnectionInvitation = await this._getIssueCredentialsbyCredentialRecordId(url, orgId); return createConnectionInvitation?.response; } catch (error) { this.logger.error(`[getIssueCredentialsbyCredentialRecordId] - error in get credentials : ${JSON.stringify(error)}`); @@ -430,12 +416,12 @@ export class IssuanceService { } } - async _getIssueCredentialsbyCredentialRecordId(url: string, apiKey: string): Promise<{ + async _getIssueCredentialsbyCredentialRecordId(url: string, orgId: string): Promise<{ response: string; }> { try { const pattern = { cmd: 'agent-get-issued-credentials-by-credentialDefinitionId' }; - const payload = { url, apiKey }; + const payload = { url, orgId }; return await this.natsCall(pattern, payload); } catch (error) { @@ -524,11 +510,6 @@ async outOfBandCredentialOffer(outOfBandCredential: OutOfBandCredentialOfferPayl throw new NotFoundException(ResponseMessages.issuance.error.organizationNotFound); } - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const errors = []; let credentialOfferResponse; const arraycredentialOfferResponse = []; @@ -545,7 +526,7 @@ async outOfBandCredentialOffer(outOfBandCredential: OutOfBandCredentialOfferPayl organisation: organisation; errors: string[]; url: string; - apiKey: string; + orgId: string; organizationDetails: organisation; } = { credentialType, @@ -557,7 +538,7 @@ async outOfBandCredentialOffer(outOfBandCredential: OutOfBandCredentialOfferPayl organisation, errors, url, - apiKey, + orgId, organizationDetails, iterator: undefined, emailId: emailId || '', @@ -624,7 +605,7 @@ async sendEmailForCredentialOffer(sendEmailCredentialOffer: SendEmailCredentialO organisation, errors, url, - apiKey, + orgId, organizationDetails } = sendEmailCredentialOffer; @@ -671,7 +652,7 @@ async sendEmailForCredentialOffer(sendEmailCredentialOffer: SendEmailCredentialO }; } - const credentialCreateOfferDetails = await this._outOfBandCredentialOffer(outOfBandIssuancePayload, url, apiKey); + const credentialCreateOfferDetails = await this._outOfBandCredentialOffer(outOfBandIssuancePayload, url, orgId); if (!credentialCreateOfferDetails) { errors.push(new NotFoundException(ResponseMessages.issuance.error.credentialOfferNotFound)); @@ -731,12 +712,12 @@ async sendEmailForCredentialOffer(sendEmailCredentialOffer: SendEmailCredentialO } } - async _outOfBandCredentialOffer(outOfBandIssuancePayload: object, url: string, apiKey: string): Promise<{ + async _outOfBandCredentialOffer(outOfBandIssuancePayload: object, url: string, orgId: string): Promise<{ response; }> { try { const pattern = { cmd: 'agent-out-of-band-credential-offer' }; - const payload = { outOfBandIssuancePayload, url, apiKey }; + const payload = { outOfBandIssuancePayload, url, orgId }; return await this.natsCall(pattern, payload); } catch (error) { this.logger.error(`[_outOfBandCredentialOffer] [NATS call]- error in out of band : ${JSON.stringify(error)}`); diff --git a/apps/ledger/src/credential-definition/credential-definition.service.ts b/apps/ledger/src/credential-definition/credential-definition.service.ts index 7f799e52c..1d19e5041 100644 --- a/apps/ledger/src/credential-definition/credential-definition.service.ts +++ b/apps/ledger/src/credential-definition/credential-definition.service.ts @@ -17,7 +17,6 @@ import { map } from 'rxjs/operators'; import { OrgAgentType } from '@credebl/enum/enum'; import { Cache } from 'cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; -import { CommonConstants } from '@credebl/common/common.constant'; @Injectable() export class CredentialDefinitionService extends BaseService { constructor( @@ -36,11 +35,7 @@ export class CredentialDefinitionService extends BaseService { // eslint-disable-next-line yoda const did = credDef.orgDid?.split(':').length >= 4 ? credDef.orgDid : orgDid; const getAgentDetails = await this.credentialDefinitionRepository.getAgentType(credDef.orgId); - // const apiKey = await this._getOrgAgentApiKey(credDef.orgId); - let apiKey:string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(credDef.orgId); - } + const userId = user.id; credDef.tag = credDef.tag.trim(); const dbResult: credential_definition = await this.credentialDefinitionRepository.getByAttribute( @@ -60,7 +55,7 @@ export class CredentialDefinitionService extends BaseService { schemaId: credDef.schemaLedgerId, issuerId: did, agentEndPoint, - apiKey, + orgId: credDef.orgId, agentType: OrgAgentType.DEDICATED }; @@ -78,7 +73,7 @@ export class CredentialDefinitionService extends BaseService { issuerId: did }, agentEndPoint, - apiKey, + orgId: credDef.orgId, agentType: OrgAgentType.SHARED }; credDefResponseFromAgentService = await this._createCredentialDefinition(CredDefPayload); @@ -181,17 +176,12 @@ export class CredentialDefinitionService extends BaseService { const { agentEndPoint } = await this.credentialDefinitionRepository.getAgentDetailsByOrgId(String(orgId)); const getAgentDetails = await this.credentialDefinitionRepository.getAgentType(String(orgId)); const orgAgentType = await this.credentialDefinitionRepository.getOrgAgentType(getAgentDetails.org_agents[0].orgAgentTypeId); - // const apiKey = await this._getOrgAgentApiKey(String(orgId)); - let apiKey:string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(String(orgId)); - } + let credDefResponse; if (OrgAgentType.DEDICATED === orgAgentType) { const getSchemaPayload = { credentialDefinitionId, - apiKey, + orgId, agentEndPoint, agentType: OrgAgentType.DEDICATED }; diff --git a/apps/ledger/src/credential-definition/interfaces/credential-definition.interface.ts b/apps/ledger/src/credential-definition/interfaces/credential-definition.interface.ts index b290bce9a..3fcd058e1 100644 --- a/apps/ledger/src/credential-definition/interfaces/credential-definition.interface.ts +++ b/apps/ledger/src/credential-definition/interfaces/credential-definition.interface.ts @@ -8,6 +8,7 @@ export interface CreateCredDefAgentRedirection { agentType?: string; apiKey?: string; agentEndPoint?: string; + orgId?: string; } export interface ITenantCredDef { @@ -24,6 +25,7 @@ export interface GetCredDefAgentRedirection { agentEndPoint?: string; agentType?: string; method?: string; + orgId?: string; } export interface GetCredDefFromTenantPayload { diff --git a/apps/ledger/src/schema/schema.interface.ts b/apps/ledger/src/schema/schema.interface.ts index ad4f58ed3..3ce52edbb 100644 --- a/apps/ledger/src/schema/schema.interface.ts +++ b/apps/ledger/src/schema/schema.interface.ts @@ -23,6 +23,7 @@ export interface CreateSchemaAgentRedirection { agentType?: string; apiKey?: string; agentEndPoint?: string; + orgId?: string; } export interface ITenantSchemaDto { @@ -40,6 +41,7 @@ export interface GetSchemaAgentRedirection { agentEndPoint?: string; agentType?: string; method?: string; + orgId?: string; } export interface GetSchemaFromTenantPayload { diff --git a/apps/ledger/src/schema/schema.service.ts b/apps/ledger/src/schema/schema.service.ts index 7d253557b..3d674470c 100644 --- a/apps/ledger/src/schema/schema.service.ts +++ b/apps/ledger/src/schema/schema.service.ts @@ -20,7 +20,6 @@ import { OrgAgentType } from '@credebl/enum/enum'; import { ICredDefWithPagination, ISchemaData, ISchemasWithPagination } from '@credebl/common/interfaces/schema.interface'; import { Cache } from 'cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; -import { CommonConstants } from '@credebl/common/common.constant'; @Injectable() export class SchemaService extends BaseService { @@ -38,10 +37,6 @@ export class SchemaService extends BaseService { orgId: string ): Promise { - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } const userId = user.id; try { @@ -144,7 +139,7 @@ export class SchemaService extends BaseService { name: schema.schemaName, issuerId, agentEndPoint, - apiKey, + orgId, agentType: OrgAgentType.DEDICATED }; schemaResponseFromAgentService = await this._createSchema(schemaPayload); @@ -162,7 +157,7 @@ export class SchemaService extends BaseService { issuerId: did }, agentEndPoint, - apiKey, + orgId, agentType: OrgAgentType.SHARED }; schemaResponseFromAgentService = await this._createSchema(schemaPayload); @@ -278,20 +273,13 @@ export class SchemaService extends BaseService { const { agentEndPoint } = await this.schemaRepository.getAgentDetailsByOrgId(orgId); const getAgentDetails = await this.schemaRepository.getAgentType(orgId); const orgAgentType = await this.schemaRepository.getOrgAgentType(getAgentDetails.org_agents[0].orgAgentTypeId); - // const apiKey = ''; - - let apiKey; - apiKey = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } let schemaResponse; if (OrgAgentType.DEDICATED === orgAgentType) { const getSchemaPayload = { schemaId, - apiKey, + orgId, agentEndPoint, agentType: OrgAgentType.DEDICATED }; @@ -304,7 +292,7 @@ export class SchemaService extends BaseService { payload: { schemaId }, agentType: OrgAgentType.SHARED, agentEndPoint, - apiKey + orgId }; schemaResponse = await this._getSchemaById(getSchemaPayload); } diff --git a/apps/verification/src/interfaces/verification.interface.ts b/apps/verification/src/interfaces/verification.interface.ts index 2a3397514..b3b22c77a 100644 --- a/apps/verification/src/interfaces/verification.interface.ts +++ b/apps/verification/src/interfaces/verification.interface.ts @@ -31,17 +31,20 @@ export interface IGetAllProofPresentations { export interface IGetProofPresentationById { url: string; - apiKey: string; + apiKey?: string; + orgId?: string; } export interface IVerifyPresentation { url: string; - apiKey: string; + apiKey?: string; + orgId?: string; } export interface IVerifiedProofData { url: string; - apiKey: string; + apiKey?: string; + orgId?: string } export interface IProofPresentationData { @@ -129,8 +132,9 @@ export interface ISendPresentationExchangeProofRequestPayload { } export interface IPresentationExchangeProofRequestPayload { url: string; - apiKey: string; + apiKey?: string; proofRequestPayload: ISendPresentationExchangeProofRequestPayload; + orgId?: string; } export interface ISendProofRequestPayload { @@ -166,7 +170,8 @@ export interface IWSendProofRequestPayload { export interface IProofRequestPayload { url: string; - apiKey: string; + apiKey?: string; + orgId?: string proofRequestPayload: ISendProofRequestPayload; } diff --git a/apps/verification/src/verification.service.ts b/apps/verification/src/verification.service.ts index b00c7e2f1..20a449863 100644 --- a/apps/verification/src/verification.service.ts +++ b/apps/verification/src/verification.service.ts @@ -121,12 +121,9 @@ export class VerificationService { const verificationMethodLabel = 'get-proof-presentation-by-id'; const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); const url = await this.getAgentUrl(verificationMethodLabel, orgAgentType, getAgentDetails?.agentEndPoint, getAgentDetails?.tenantId, '', proofId); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const payload = { apiKey, url }; + + const payload = { orgId, url }; const getProofPresentationById = await this._getProofPresentationById(payload); return getProofPresentationById?.response; @@ -222,11 +219,8 @@ export class VerificationService { const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); const verificationMethodLabel = 'request-proof'; const url = await this.getAgentUrl(verificationMethodLabel, orgAgentType, getAgentDetails?.agentEndPoint, getAgentDetails?.tenantId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(requestProof.orgId); - } - const payload = { apiKey, url, proofRequestPayload }; + + const payload = { orgId: requestProof.orgId, url, proofRequestPayload }; const getProofPresentationById = await this._sendProofRequest(payload); return getProofPresentationById?.response; @@ -268,15 +262,12 @@ export class VerificationService { try { const getAgentData = await this.verificationRepository.getAgentEndPoint(orgId); const orgAgentTypeData = await this.verificationRepository.getOrgAgentType(getAgentData?.orgAgentTypeId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - + const verificationMethod = 'accept-presentation'; - + const url = await this.getAgentUrl(verificationMethod, orgAgentTypeData, getAgentData?.agentEndPoint, getAgentData?.tenantId, '', proofId); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const payload = { apiKey, url }; + + const payload = { orgId, url }; const getProofPresentationById = await this._verifyPresentation(payload); return getProofPresentationById?.response; } catch (error) { @@ -351,12 +342,9 @@ export class VerificationService { outOfBandRequestProof['label'] = label; const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); const verificationMethodLabel = 'create-request-out-of-band'; const url = await this.getAgentUrl(verificationMethodLabel, orgAgentType, getAgentDetails?.agentEndPoint, getAgentDetails?.tenantId); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(user.orgId); - } + const { isShortenUrl, type, ...updateOutOfBandRequestProof } = outOfBandRequestProof; outOfBandRequestProof.autoAcceptProof = outOfBandRequestProof.autoAcceptProof || 'always'; @@ -366,7 +354,7 @@ export class VerificationService { if (ProofRequestType.INDY === type) { updateOutOfBandRequestProof.protocolVersion = updateOutOfBandRequestProof.protocolVersion || 'v1'; payload = { - apiKey, + orgId: user.orgId, url, proofRequestPayload: updateOutOfBandRequestProof }; @@ -375,7 +363,7 @@ export class VerificationService { if (ProofRequestType.PRESENTATIONEXCHANGE === type) { payload = { - apiKey, + orgId: user.orgId, url, proofRequestPayload: { protocolVersion:outOfBandRequestProof.protocolVersion || 'v2', @@ -713,12 +701,8 @@ export class VerificationService { let schemaId; const orgAgentType = await this.verificationRepository.getOrgAgentType(getAgentDetails?.orgAgentTypeId); const url = await this.getAgentUrl(verificationMethodLabel, orgAgentType, getAgentDetails?.agentEndPoint, getAgentDetails?.tenantId, '', proofId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this._getOrgAgentApiKey(orgId); - } - const payload = { apiKey, url }; + + const payload = { orgId, url }; const getProofPresentationById = await this._getVerifiedProofDetails(payload); From d2f29ebf279bfe0cbfc83a97a13296f2425f44af Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Thu, 14 Mar 2024 15:17:01 +0530 Subject: [PATCH 02/11] fix: added the token validation with encryption on the wallet and DID Signed-off-by: KulkarniShashank --- .../src/agent-service.service.ts | 56 +++++++------------ 1 file changed, 19 insertions(+), 37 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index e899cbf8f..e2c860cd1 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -784,6 +784,7 @@ export class AgentServiceService { const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG); const getPlatformAgentEndPoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; + const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); const { label } = payload; const createTenantOptions = { @@ -793,7 +794,7 @@ export class AgentServiceService { const tenantDetails = await this.commonService.httpPost( `${getPlatformAgentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`, createTenantOptions, - { headers: { 'authorization': platformAdminSpinnedUp.org_agents[0].apiKey } } + { headers: { 'authorization': getDcryptedToken } } ); return tenantDetails; @@ -812,20 +813,17 @@ export class AgentServiceService { async createDid(payload: IDidCreate, orgId: string, user: IUserRequestInterface): Promise { try { const agentDetails = await this.agentServiceRepository.getOrgAgentDetails(orgId); - let apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (!apiKey || null === apiKey || undefined === apiKey) { - apiKey = await this.getOrgAgentApiKey(orgId); - } + + const getApiKey = await this.getOrgAgentApiKey(orgId); const getOrgAgentType = await this.agentServiceRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); let url; - if (getOrgAgentType.agent === OrgAgentType.DEDICATED) { url = `${agentDetails.agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; } else if (getOrgAgentType.agent === OrgAgentType.SHARED) { url = `${agentDetails.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${agentDetails.tenantId}`; } const didDetails = await this.commonService.httpPost(url, payload, - { headers: { 'authorization': apiKey } } + { headers: { 'authorization': getApiKey } } ); return didDetails; @@ -854,10 +852,11 @@ export class AgentServiceService { ); const getPlatformAgentEndPoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; + const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); const url = `${getPlatformAgentEndPoint}${CommonConstants.CREATE_POLYGON_SECP256k1_KEY}`; - const createKeyPairResponse = await this.commonService.httpPost(url, {}, { headers: { 'authorization': platformAdminSpinnedUp.org_agents[0].apiKey } }); + const createKeyPairResponse = await this.commonService.httpPost(url, {}, { headers: { 'authorization': getDcryptedToken } }); return createKeyPairResponse; } catch (error) { this.logger.error(`error in createSecp256k1KeyPair : ${JSON.stringify(error)}`); @@ -907,8 +906,8 @@ export class AgentServiceService { delete WalletSetupPayload.ledgerId; - const walletResponseDetails = await this._createTenantWallet(walletLabel, platformAdminSpinnedUp.org_agents[0].agentEndPoint, platformAdminSpinnedUp.org_agents[0].apiKey); - const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); + const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); + const walletResponseDetails = await this._createTenantWallet(walletLabel, platformAdminSpinnedUp.org_agents[0].agentEndPoint, getDcryptedToken); if (!walletResponseDetails && !walletResponseDetails.id) { throw new InternalServerErrorException('Error while creating the wallet'); } @@ -1006,9 +1005,7 @@ export class AgentServiceService { issuerId: payload.issuerId }; schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': getApiKey } }) - .then(async (schema) => { - return schema; - }) + .then(async (schema) => schema) .catch(error => { throw new InternalServerErrorException( ResponseMessages.agent.error.agentDown, @@ -1026,9 +1023,7 @@ export class AgentServiceService { issuerId: payload.payload.issuerId }; schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': getApiKey } }) - .then(async (schema) => { - return schema; - }) + .then(async (schema) => schema) .catch(error => { throw new InternalServerErrorException( ResponseMessages.agent.error.agentDown, @@ -1051,17 +1046,13 @@ export class AgentServiceService { if (OrgAgentType.DEDICATED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_SCHEMA_BY_ID.replace('#', `${payload.schemaId}`)}`; schemaResponse = await this.commonService.httpGet(url, payload.schemaId) - .then(async (schema) => { - return schema; - }); + .then(async (schema) => schema); } else if (OrgAgentType.SHARED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_SCHEMA}`.replace('@', `${payload.payload.schemaId}`).replace('#', `${payload.tenantId}`); schemaResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async (schema) => { - return schema; - }); + .then(async (schema) => schema); } return schemaResponse; } catch (error) { @@ -1085,9 +1076,7 @@ export class AgentServiceService { }; credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': getApiKey } }) - .then(async (credDef) => { - return credDef; - }); + .then(async (credDef) => credDef); } else if (OrgAgentType.SHARED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_CRED_DEF}`.replace('#', `${payload.tenantId}`); @@ -1097,9 +1086,7 @@ export class AgentServiceService { issuerId: payload.payload.issuerId }; credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': getApiKey } }) - .then(async (credDef) => { - return credDef; - }); + .then(async (credDef) => credDef); } return credDefResponse; @@ -1117,16 +1104,12 @@ export class AgentServiceService { if (OrgAgentType.DEDICATED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_CRED_DEF_BY_ID.replace('#', `${payload.credentialDefinitionId}`)}`; credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async (credDef) => { - return credDef; - }); + .then(async (credDef) => credDef); } else if (OrgAgentType.SHARED === payload.agentType) { const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CRED_DEF}`.replace('@', `${payload.payload.credentialDefinitionId}`).replace('#', `${payload.tenantId}`); credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async (credDef) => { - return credDef; - }); + .then(async (credDef) => credDef); } return credDefResponse; } catch (error) { @@ -1462,13 +1445,12 @@ export class AgentServiceService { } } - private async getOrgAgentApiKey(orgId: string): Promise { + async getOrgAgentApiKey(orgId: string): Promise { try { let agentApiKey; const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); const apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (apiKey) { const getDcryptedToken = await this.commonService.decryptPassword(apiKey); return getDcryptedToken; @@ -1494,7 +1476,7 @@ export class AgentServiceService { throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); } - await this.cacheService.set(CommonConstants.CACHE_APIKEY_KEY, agentApiKey, CommonConstants.CACHE_TTL_SECONDS); + await this.cacheService.set(CommonConstants.CACHE_APIKEY_KEY, agentApiKey, 0); const getDcryptedToken = await this.commonService.decryptPassword(agentApiKey); return getDcryptedToken; From be68d5072c250c06f0a8150c6b6cfe4772eca1b2 Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Fri, 15 Mar 2024 14:27:23 +0530 Subject: [PATCH 03/11] fix: solved the platform-admin agent spin-up Signed-off-by: KulkarniShashank --- .../src/agent-service.service.ts | 1036 +++++++++-------- libs/common/src/common.constant.ts | 3 +- 2 files changed, 565 insertions(+), 474 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index fa1ef4037..b814a34a0 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -19,7 +19,38 @@ import * as dotenv from 'dotenv'; import * as fs from 'fs'; import { map } from 'rxjs/operators'; dotenv.config(); -import { IGetCredDefAgentRedirection, IConnectionDetails, IUserRequestInterface, IAgentSpinupDto, IStoreOrgAgentDetails, ITenantCredDef, ITenantDto, ITenantSchema, IWalletProvision, ISendProofRequestPayload, IIssuanceCreateOffer, IOutOfBandCredentialOffer, IAgentSpinUpSatus, ICreateTenant, IAgentStatus, ICreateOrgAgent, IOrgAgentsResponse, IProofPresentation, IAgentProofRequest, IPresentation, IReceiveInvitationUrl, IReceiveInvitation, IQuestionPayload, IDidCreate, IWallet, ITenantRecord, IPlatformAgent, LedgerListResponse, IOrgLedgers, IStoreOrgAgent } from './interface/agent-service.interface'; +import { + IGetCredDefAgentRedirection, + IConnectionDetails, + IUserRequestInterface, + IAgentSpinupDto, + IStoreOrgAgentDetails, + ITenantCredDef, + ITenantDto, + ITenantSchema, + IWalletProvision, + ISendProofRequestPayload, + IIssuanceCreateOffer, + IOutOfBandCredentialOffer, + IAgentSpinUpSatus, + ICreateTenant, + IAgentStatus, + ICreateOrgAgent, + IOrgAgentsResponse, + IProofPresentation, + IAgentProofRequest, + IPresentation, + IReceiveInvitationUrl, + IReceiveInvitation, + IQuestionPayload, + IDidCreate, + IWallet, + ITenantRecord, + IPlatformAgent, + LedgerListResponse, + IOrgLedgers, + IStoreOrgAgent +} from './interface/agent-service.interface'; import { AgentSpinUpStatus, AgentType, DidMethod, Ledgers, OrgAgentType } from '@credebl/enum/enum'; import { AgentServiceRepository } from './repositories/agent-service.repository'; import { ledgers, org_agents, organisation, platform_config } from '@prisma/client'; @@ -39,11 +70,9 @@ import { ledgerName } from '@credebl/common/cast.helper'; import { InvitationMessage } from '@credebl/common/interfaces/agent-service.interface'; import * as CryptoJS from 'crypto-js'; - @Injectable() @WebSocketGateway() export class AgentServiceService { - private readonly logger = new Logger('WalletService'); constructor( @@ -52,24 +81,21 @@ export class AgentServiceService { private readonly connectionService: ConnectionService, @Inject('NATS_CLIENT') private readonly agentServiceProxy: ClientProxy, @Inject(CACHE_MANAGER) private cacheService: Cache - ) { } + ) {} async ReplaceAt(input, search, replace, start, end): Promise { - return input.slice(0, start) - + input.slice(start, end).replace(search, replace) - + input.slice(end); + return input.slice(0, start) + input.slice(start, end).replace(search, replace) + input.slice(end); } /** * Spinup the agent by organization - * @param agentSpinupDto - * @param user + * @param agentSpinupDto + * @param user * @returns Get agent status */ async walletProvision(agentSpinupDto: IAgentSpinupDto, user: IUserRequestInterface): Promise { let agentProcess: ICreateOrgAgent; try { - // Invoke an internal function to create wallet await this.processWalletProvision(agentSpinupDto, user); const agentStatusResponse = { @@ -78,7 +104,6 @@ export class AgentServiceService { return agentStatusResponse; } catch (error) { - // Invoke an internal function to handle error to create wallet this.handleErrorOnWalletProvision(agentSpinupDto, error, agentProcess); throw new RpcException(error.response ? error.response : error); @@ -91,17 +116,16 @@ export class AgentServiceService { let agentProcess: ICreateOrgAgent; let getOrgAgent; try { - const [platformConfig, getAgentType, ledgerIdData] = await Promise.all([ this.agentServiceRepository.getPlatformConfigDetails(), this.agentServiceRepository.getAgentTypeDetails(), - this.agentServiceRepository.getLedgerDetails(agentSpinupDto.ledgerName ? agentSpinupDto.ledgerName : [Ledgers.Indicio_Demonet]) + this.agentServiceRepository.getLedgerDetails( + agentSpinupDto.ledgerName ? agentSpinupDto.ledgerName : [Ledgers.Indicio_Demonet] + ) ]); - + let orgData; if (!user?.userId && agentSpinupDto?.platformAdminEmail) { - - // Get Platform admin user by platform admin email platformAdminUser = await this.agentServiceRepository.getPlatfomAdminUser(agentSpinupDto?.platformAdminEmail); @@ -114,14 +138,12 @@ export class AgentServiceService { const platformAdminOrgDetails = await this.agentServiceRepository.getPlatfomOrg(agentSpinupDto?.orgName); if (agentSpinupDto.orgId) { - // Get organization details getOrgAgent = await this.agentServiceRepository.getAgentDetails(agentSpinupDto.orgId); // Get organization data by orgId orgData = await this.agentServiceRepository.getOrgDetails(agentSpinupDto.orgId); } else { - // Get platform organization details getOrgAgent = await this.agentServiceRepository.getAgentDetails(platformAdminOrgDetails); @@ -129,27 +151,28 @@ export class AgentServiceService { orgData = await this.agentServiceRepository.getOrgDetails(platformAdminOrgDetails); } - agentSpinupDto.ledgerId = agentSpinupDto.ledgerId?.length ? agentSpinupDto.ledgerId : ledgerIdData.map(ledger => ledger?.id); + agentSpinupDto.ledgerId = agentSpinupDto.ledgerId?.length + ? agentSpinupDto.ledgerId + : ledgerIdData.map((ledger) => ledger?.id); // Get genesis URL and ledger details const ledgerDetails = await this.agentServiceRepository.getGenesisUrl(agentSpinupDto.ledgerId); if (AgentSpinUpStatus.PROCESSED === getOrgAgent?.agentSpinUpStatus) { - throw new BadRequestException( - ResponseMessages.agent.error.walletAlreadyProcessing, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.walletAlreadyProcessing, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } if (AgentSpinUpStatus.COMPLETED === getOrgAgent?.agentSpinUpStatus) { - throw new ConflictException( - ResponseMessages.agent.error.walletAlreadyCreated, - { cause: new Error(), description: ResponseMessages.errorMessages.conflict } - ); + throw new ConflictException(ResponseMessages.agent.error.walletAlreadyCreated, { + cause: new Error(), + description: ResponseMessages.errorMessages.conflict + }); } if (!agentSpinupDto.orgId) { - if (platformAdminOrgDetails) { agentSpinupDto.orgId = platformAdminOrgDetails; } @@ -157,7 +180,9 @@ export class AgentServiceService { agentSpinupDto.agentType = agentSpinupDto.agentType || getAgentType; agentSpinupDto.tenant = agentSpinupDto.tenant || false; - agentSpinupDto.ledgerName = agentSpinupDto.ledgerName?.length ? agentSpinupDto.ledgerName : [Ledgers.Indicio_Demonet]; + agentSpinupDto.ledgerName = agentSpinupDto.ledgerName?.length + ? agentSpinupDto.ledgerName + : [Ledgers.Indicio_Demonet]; // Invoke function for validate platform configuration this.validatePlatformConfig(platformConfig); @@ -167,7 +192,14 @@ export class AgentServiceService { const apiEndpoint = platformConfig?.apiEndpoint; // Create payload for the wallet create and store payload - const walletProvisionPayload = await this.prepareWalletProvisionPayload(agentSpinupDto, externalIp, apiEndpoint, inboundEndpoint, ledgerDetails, orgData); + const walletProvisionPayload = await this.prepareWalletProvisionPayload( + agentSpinupDto, + externalIp, + apiEndpoint, + inboundEndpoint, + ledgerDetails, + orgData + ); // Socket connection const socket: Socket = await this.initSocketConnection(`${process.env.SOCKET_HOST}`); @@ -177,8 +209,16 @@ export class AgentServiceService { agentProcess = await this.createOrgAgent(agentSpinUpStatus, userId); // AFJ agent spin-up - this._agentSpinup(walletProvisionPayload, agentSpinupDto, platformConfig?.sgApiKey, orgData, user, socket, agentSpinupDto.ledgerId, agentProcess); - + this._agentSpinup( + walletProvisionPayload, + agentSpinupDto, + platformConfig?.sgApiKey, + orgData, + user, + socket, + agentSpinupDto.ledgerId, + agentProcess + ); } catch (error) { this.handleErrorOnWalletProvision(agentSpinupDto, error, agentProcess); throw error; @@ -188,34 +228,34 @@ export class AgentServiceService { validatePlatformConfig(platformConfig: platform_config): void { if (!platformConfig) { this.logger.error(`Platform configuration is missing or invalid`); - throw new BadRequestException( - ResponseMessages.agent.error.platformConfiguration, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.platformConfiguration, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } if (!platformConfig.apiEndpoint) { this.logger.error(`API endpoint is missing in the platform configuration`); - throw new BadRequestException( - ResponseMessages.agent.error.apiEndpoint, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.apiEndpoint, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } if (!platformConfig.externalIp) { this.logger.error(`External IP is missing in the platform configuration`); - throw new BadRequestException( - ResponseMessages.agent.error.externalIp, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.externalIp, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } if (typeof platformConfig.externalIp !== 'string') { this.logger.error(`External IP must be a string`); - throw new BadRequestException( - ResponseMessages.agent.error.externalIp, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.externalIp, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } } @@ -223,10 +263,10 @@ export class AgentServiceService { try { if (!agentProcess) { this.logger.error(`Agent process is invalid or not in a completed state`); - throw new BadRequestException( - ResponseMessages.agent.error.externalIp, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.externalIp, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } } catch (error) { this.logger.error(`Error validating agent process: ${error.message}`); @@ -237,12 +277,10 @@ export class AgentServiceService { emitAgentSpinupInitiatedEvent(agentSpinupDto: IAgentSpinupDto, socket: Socket): void { try { if (agentSpinupDto.clientSocketId) { - socket.emit('agent-spinup-process-initiated', { clientId: agentSpinupDto.clientSocketId }); // Log or perform other actions after emitting the event this.logger.log(`Agent spinup initiated event emitted for orgId ${agentSpinupDto.orgId}`); } - } catch (error) { this.logger.error(`Error emitting agent-spinup-initiated event: ${error.message}`); throw error; @@ -257,7 +295,7 @@ export class AgentServiceService { ledgerDetails: ledgers[], orgData: organisation ): Promise { - const ledgerArray = ledgerDetails.map(ledger => ({ + const ledgerArray = ledgerDetails.map((ledger) => ({ genesisTransactions: ledger.poolConfig, indyNamespace: ledger.indyNamespace })); @@ -307,13 +345,16 @@ export class AgentServiceService { this.logger.log(`Organization agent created with status: ${agentSpinUpStatus}`); return agentProcess; } catch (error) { - this.logger.error(`Error creating organization agent: ${error.message}`); throw error; } } - private async handleErrorOnWalletProvision(agentSpinupDto: IAgentSpinupDto, error: Error, agentProcess: ICreateOrgAgent): Promise { + private async handleErrorOnWalletProvision( + agentSpinupDto: IAgentSpinupDto, + error: Error, + agentProcess: ICreateOrgAgent + ): Promise { if (agentProcess) { const socket = await this.initSocketConnection(`${process.env.SOCKET_HOST}`); @@ -329,42 +370,49 @@ export class AgentServiceService { try { socket.emit('error-in-wallet-creation-process', { clientId: agentSpinupDto.clientSocketId, error }); this.logger.error(`Error in wallet creation process emitted for orgId ${agentSpinupDto.orgId}: ${error.message}`); - } catch (emitError) { this.logger.error(`Error emitting error-in-wallet-creation-process event: ${emitError.message}`); throw emitError; } } - async _agentSpinup(walletProvisionPayload: IWalletProvision, agentSpinupDto: IAgentSpinupDto, orgApiKey: string, orgData: organisation, user: IUserRequestInterface, socket: Socket, ledgerId: string[], agentProcess: ICreateOrgAgent): Promise { + async _agentSpinup( + walletProvisionPayload: IWalletProvision, + agentSpinupDto: IAgentSpinupDto, + orgApiKey: string, + orgData: organisation, + user: IUserRequestInterface, + socket: Socket, + ledgerId: string[], + agentProcess: ICreateOrgAgent + ): Promise { let ledgerIdData = []; try { if (agentSpinupDto.method !== DidMethod.KEY && agentSpinupDto.method !== DidMethod.WEB) { + const { network } = agentSpinupDto; + const ledger = await ledgerName(network); + const ledgerList = (await this._getALlLedgerDetails()) as unknown as LedgerListResponse; + const isLedgerExist = ledgerList.response.find((existingLedgers) => existingLedgers.name === ledger); + if (!isLedgerExist) { + throw new BadRequestException(ResponseMessages.agent.error.invalidLedger, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); + } - const { network } = agentSpinupDto; - const ledger = await ledgerName(network); - const ledgerList = await this._getALlLedgerDetails() as unknown as LedgerListResponse; - const isLedgerExist = ledgerList.response.find((existingLedgers) => existingLedgers.name === ledger); - if (!isLedgerExist) { - throw new BadRequestException( - ResponseMessages.agent.error.invalidLedger, - { cause: new Error(), description: ResponseMessages.errorMessages.notFound } - ); + ledgerIdData = await this.agentServiceRepository.getLedgerDetails(ledger); } - - ledgerIdData = await this.agentServiceRepository.getLedgerDetails(ledger); - } /** - * Invoke wallet create and provision with agent + * Invoke wallet create and provision with agent */ const walletProvision = await this._walletProvision(walletProvisionPayload); if (!walletProvision?.response) { this.logger.error(`Agent not able to spin-up`); - throw new BadRequestException( - ResponseMessages.agent.error.notAbleToSpinup, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.notAbleToSpinup, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } const agentDetails = walletProvision.response; const agentEndPoint = `${process.env.API_GATEWAY_PROTOCOL}://${agentDetails.agentEndPoint}`; @@ -393,17 +441,18 @@ export class AgentServiceService { role: agentSpinupDto.role, network: agentSpinupDto.network, keyType: agentSpinupDto.keyType, - ledgerId: ledgerIdData ? ledgerIdData.map(item => item.id) : null, + ledgerId: ledgerIdData ? ledgerIdData.map((item) => item.id) : null, did: agentSpinupDto.did, id: agentProcess?.id }; /** - * Store organization agent details + * Store organization agent details */ const storeAgentDetails = await this._storeOrgAgentDetails(agentPayload); if (storeAgentDetails) { - - const filePath = `${process.cwd()}${process.env.AFJ_AGENT_TOKEN_PATH}${orgData.id}_${orgData.name.split(' ').join('_')}.json`; + const filePath = `${process.cwd()}${process.env.AFJ_AGENT_TOKEN_PATH}${orgData.id}_${orgData.name + .split(' ') + .join('_')}.json`; if (agentDetails?.agentToken) { fs.unlink(filePath, (err) => { if (err) { @@ -427,10 +476,10 @@ export class AgentServiceService { } } else { this.logger.error(`Agent not able to spin-up`); - throw new BadRequestException( - ResponseMessages.agent.error.notAbleToSpinup, - { cause: new Error(), description: ResponseMessages.errorMessages.badRequest } - ); + throw new BadRequestException(ResponseMessages.agent.error.notAbleToSpinup, { + cause: new Error(), + description: ResponseMessages.errorMessages.badRequest + }); } } catch (error) { if (agentSpinupDto.clientSocketId) { @@ -439,7 +488,7 @@ export class AgentServiceService { if (agentProcess && agentProcess?.id) { /** - * If getting error remove organization agent + * If getting error remove organization agent */ await this.agentServiceRepository.removeOrgAgent(agentProcess?.id); } @@ -449,7 +498,6 @@ export class AgentServiceService { async _storeOrgAgentDetails(payload: IStoreOrgAgentDetails): Promise { try { - /** * Get orgaization agent type and agent details */ @@ -476,24 +524,36 @@ export class AgentServiceService { } } - private async _getAgentDid(payload: IStoreOrgAgentDetails): Promise { - const { agentEndPoint, apiKey, ledgerId, seed, keyType, method, network, role, did } = payload; + const { agentEndPoint, apiKey, ledgerId, seed, keyType, method, network, role, did } = payload; const writeDid = 'write-did'; const ledgerDetails = await this.agentServiceRepository.getGenesisUrl(ledgerId); const agentDidWriteUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; return this._retryAgentSpinup(agentDidWriteUrl, apiKey, writeDid, seed, keyType, method, network, role, did); - } private async _getDidMethod(payload: IStoreOrgAgentDetails, agentDid: object): Promise { - const { agentEndPoint, apiKey, seed, keyType, method, network, role } = payload; + const { agentEndPoint, apiKey, seed, keyType, method, network, role } = payload; const getDidDoc = 'get-did-doc'; const getDidMethodUrl = `${agentEndPoint}${CommonConstants.URL_AGENT_GET_DID}/${agentDid['did']}`; - return this._retryAgentSpinup(getDidMethodUrl, apiKey, getDidDoc, seed, keyType, method, network, role, `${agentDid['did']}`); + return this._retryAgentSpinup( + getDidMethodUrl, + apiKey, + getDidDoc, + seed, + keyType, + method, + network, + role, + `${agentDid['did']}` + ); } - private _buildStoreOrgAgentData(payload: IStoreOrgAgentDetails, getDidMethod: object, orgAgentTypeId: string): IStoreOrgAgentDetails { + private _buildStoreOrgAgentData( + payload: IStoreOrgAgentDetails, + getDidMethod: object, + orgAgentTypeId: string + ): IStoreOrgAgentDetails { return { did: getDidMethod['didDocument']?.id, verkey: getDidMethod['didDocument']?.verificationMethod[0]?.publicKeyBase58, @@ -524,35 +584,49 @@ export class AgentServiceService { } if (payload && payload?.id) { - this.agentServiceRepository.removeOrgAgent(payload?.id); } this.logger.error(`[_storeOrgAgentDetails] - Error in store agent details : ${JSON.stringify(error)}`); } - - async _retryAgentSpinup(agentUrl: string, apiKey: string, agentApiState: string, seed: string, keyType: string, method: string, network: string, role: string, did: string): Promise { + async _retryAgentSpinup( + agentUrl: string, + apiKey: string, + agentApiState: string, + seed: string, + keyType: string, + method: string, + network: string, + role: string, + did: string + ): Promise { const retryOptions = { retries: 10 }; try { - const getDcryptedToken = await this.commonService.decryptPassword(apiKey); + const getDcryptedToken = await this.commonService.decryptPassword(apiKey); return retry(async () => { if (agentApiState === 'write-did') { - return this.commonService.httpPost(agentUrl, { seed, keyType, method, network, role, did}, { headers: { 'authorization': getDcryptedToken } }); + return this.commonService.httpPost( + agentUrl, + { seed, keyType, method, network, role, did }, + { headers: { authorization: getDcryptedToken } } + ); } else if (agentApiState === 'get-did-doc') { - return this.commonService.httpGet(agentUrl, { headers: { 'authorization': getDcryptedToken } }); + return this.commonService.httpGet(agentUrl, { headers: { authorization: getDcryptedToken } }); } }, retryOptions); - } catch (error) { throw error; } } - - async _createLegacyConnectionInvitation(orgId: string, user: IUserRequestInterface, label: string): Promise<{ + async _createLegacyConnectionInvitation( + orgId: string, + user: IUserRequestInterface, + label: string + ): Promise<{ response; }> { try { @@ -563,18 +637,20 @@ export class AgentServiceService { return this.agentServiceProxy .send(pattern, payload) .pipe( - map((response) => ( - { - response - })) - ).toPromise() - .catch(error => { + map((response) => ({ + response + })) + ) + .toPromise() + .catch((error) => { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( { status: error.statusCode, error: error.message - }, error.error); + }, + error.error + ); }); } catch (error) { this.logger.error(`error in create-connection in wallet provision : ${JSON.stringify(error)}`); @@ -592,25 +668,26 @@ export class AgentServiceService { return this.agentServiceProxy .send(pattern, payload) .pipe( - map((response) => ( - { - response - })) - ).toPromise() - .catch(error => { + map((response) => ({ + response + })) + ) + .toPromise() + .catch((error) => { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( { status: error.statusCode, error: error.message - }, error.error); + }, + error.error + ); }); } catch (error) { this.logger.error(`error in while fetching all the ledger details : ${JSON.stringify(error)}`); } } - async _walletProvision(payload: IWalletProvision): Promise<{ response; }> { @@ -621,18 +698,20 @@ export class AgentServiceService { return this.agentServiceProxy .send(pattern, payload) .pipe( - map((response) => ( - { - response - })) - ).toPromise() - .catch(error => { + map((response) => ({ + response + })) + ) + .toPromise() + .catch((error) => { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( { status: error.statusCode, error: error.message - }, error.error); + }, + error.error + ); }); } catch (error) { this.logger.error(`error in wallet provision : ${JSON.stringify(error)}`); @@ -642,13 +721,12 @@ export class AgentServiceService { /** * Create tenant (Shared agent) - * @param payload - * @param user + * @param payload + * @param user * @returns Get agent status */ async createTenant(payload: ITenantDto, user: IUserRequestInterface): Promise { try { - const agentStatusResponse = { agentSpinupStatus: AgentSpinUpStatus.PROCESSED }; @@ -657,18 +735,18 @@ export class AgentServiceService { if (AgentSpinUpStatus.COMPLETED === getOrgAgent?.agentSpinUpStatus) { this.logger.error(`Your wallet is already been created.`); - throw new ConflictException( - ResponseMessages.agent.error.walletAlreadyCreated, - { cause: new Error(), description: ResponseMessages.errorMessages.conflict } - ); + throw new ConflictException(ResponseMessages.agent.error.walletAlreadyCreated, { + cause: new Error(), + description: ResponseMessages.errorMessages.conflict + }); } if (AgentSpinUpStatus.PROCESSED === getOrgAgent?.agentSpinUpStatus) { this.logger.error(`Your wallet is already processing.`); - throw new ConflictException( - ResponseMessages.agent.error.walletAlreadyProcessing, - { cause: new Error(), description: ResponseMessages.errorMessages.conflict } - ); + throw new ConflictException(ResponseMessages.agent.error.walletAlreadyProcessing, { + cause: new Error(), + description: ResponseMessages.errorMessages.conflict + }); } // Create tenant @@ -682,124 +760,123 @@ export class AgentServiceService { /** * Create tenant (Shared agent) - * @param payload - * @param user + * @param payload + * @param user * @returns Get agent status */ - async _createTenant(payload: ITenantDto, user: IUserRequestInterface): Promise { - let agentProcess; - let ledgerIdData = []; - try { - if (payload.method !== DidMethod.KEY && payload.method !== DidMethod.WEB) { - - const { network } = payload; - const ledger = await ledgerName(network); - const ledgerList = await this._getALlLedgerDetails() as unknown as LedgerListResponse; - const isLedgerExist = ledgerList.response.find((existingLedgers) => existingLedgers.name === ledger); - if (!isLedgerExist) { - throw new BadRequestException( - ResponseMessages.agent.error.invalidLedger, - { cause: new Error(), description: ResponseMessages.errorMessages.notFound } - ); - } - - ledgerIdData = await this.agentServiceRepository.getLedgerDetails(ledger); + async _createTenant(payload: ITenantDto, user: IUserRequestInterface): Promise { + let agentProcess; + let ledgerIdData = []; + try { + if (payload.method !== DidMethod.KEY && payload.method !== DidMethod.WEB) { + const { network } = payload; + const ledger = await ledgerName(network); + const ledgerList = (await this._getALlLedgerDetails()) as unknown as LedgerListResponse; + const isLedgerExist = ledgerList.response.find((existingLedgers) => existingLedgers.name === ledger); + if (!isLedgerExist) { + throw new BadRequestException(ResponseMessages.agent.error.invalidLedger, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); } - const agentSpinUpStatus = AgentSpinUpStatus.PROCESSED; - - // Create and stored agent details - agentProcess = await this.agentServiceRepository.createOrgAgent(agentSpinUpStatus, user?.id); - - // Get platform admin details - const platformAdminSpinnedUp = await this.getPlatformAdminAndNotify(payload.clientSocketId); - - payload.endpoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; - // Create tenant wallet and DID - const tenantDetails = await this.createTenantAndNotify(payload, platformAdminSpinnedUp); - if (!tenantDetails?.walletResponseDetails?.id || !tenantDetails?.DIDCreationOption?.did) { - this.logger.error(`Error in getting wallet id and wallet did`); - throw new NotFoundException( - ResponseMessages.agent.error.notAbleToSpinUpAgent, - { cause: new Error(), description: ResponseMessages.errorMessages.notFound } - ); - } + ledgerIdData = await this.agentServiceRepository.getLedgerDetails(ledger); + } - if (AgentSpinUpStatus.COMPLETED !== platformAdminSpinnedUp.org_agents[0].agentSpinUpStatus) { - this.logger.error(`Platform-admin agent is not spun-up`); - throw new NotFoundException( - ResponseMessages.agent.error.platformAdminNotAbleToSpinp, - { cause: new Error(), description: ResponseMessages.errorMessages.notFound } - ); - } - // Get shared agent type - const orgAgentTypeId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); - // Get agent type details - const agentTypeId = await this.agentServiceRepository.getAgentTypeId(AgentType.AFJ); - - const storeOrgAgentData: IStoreOrgAgentDetails = { - did: tenantDetails.DIDCreationOption.did, - isDidPublic: true, - agentSpinUpStatus: AgentSpinUpStatus.COMPLETED, - agentsTypeId: agentTypeId, - orgId: payload.orgId, - agentEndPoint: platformAdminSpinnedUp.org_agents[0].agentEndPoint, - orgAgentTypeId, - tenantId: tenantDetails.walletResponseDetails['id'], - walletName: payload.label, - ledgerId: ledgerIdData ? ledgerIdData.map(item => item.id) : null, - id: agentProcess?.id - }; - - // Get organization data - const getOrganization = await this.agentServiceRepository.getOrgDetails(payload.orgId); - - this.notifyClientSocket('agent-spinup-process-completed', payload.clientSocketId); - - await this.agentServiceRepository.storeOrgAgentDetails(storeOrgAgentData); - - this.notifyClientSocket('invitation-url-creation-started', payload.clientSocketId); - - // Create the legacy connection invitation - await this._createLegacyConnectionInvitation(payload.orgId, user, getOrganization.name); - - this.notifyClientSocket('invitation-url-creation-success', payload.clientSocketId); - - } catch (error) { - this.handleError(error, payload.clientSocketId); - - if (agentProcess && agentProcess?.id) { - this.agentServiceRepository.removeOrgAgent(agentProcess?.id); - } - throw error; + const agentSpinUpStatus = AgentSpinUpStatus.PROCESSED; + + // Create and stored agent details + agentProcess = await this.agentServiceRepository.createOrgAgent(agentSpinUpStatus, user?.id); + + // Get platform admin details + const platformAdminSpinnedUp = await this.getPlatformAdminAndNotify(payload.clientSocketId); + + payload.endpoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; + // Create tenant wallet and DID + const tenantDetails = await this.createTenantAndNotify(payload, platformAdminSpinnedUp); + if (!tenantDetails?.walletResponseDetails?.id || !tenantDetails?.DIDCreationOption?.did) { + this.logger.error(`Error in getting wallet id and wallet did`); + throw new NotFoundException(ResponseMessages.agent.error.notAbleToSpinUpAgent, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); } + + if (AgentSpinUpStatus.COMPLETED !== platformAdminSpinnedUp.org_agents[0].agentSpinUpStatus) { + this.logger.error(`Platform-admin agent is not spun-up`); + throw new NotFoundException(ResponseMessages.agent.error.platformAdminNotAbleToSpinp, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); + } + // Get shared agent type + const orgAgentTypeId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); + // Get agent type details + const agentTypeId = await this.agentServiceRepository.getAgentTypeId(AgentType.AFJ); + + const storeOrgAgentData: IStoreOrgAgentDetails = { + did: tenantDetails.DIDCreationOption.did, + isDidPublic: true, + agentSpinUpStatus: AgentSpinUpStatus.COMPLETED, + agentsTypeId: agentTypeId, + orgId: payload.orgId, + agentEndPoint: platformAdminSpinnedUp.org_agents[0].agentEndPoint, + orgAgentTypeId, + tenantId: tenantDetails.walletResponseDetails['id'], + walletName: payload.label, + ledgerId: ledgerIdData ? ledgerIdData.map((item) => item.id) : null, + id: agentProcess?.id + }; + + // Get organization data + const getOrganization = await this.agentServiceRepository.getOrgDetails(payload.orgId); + + this.notifyClientSocket('agent-spinup-process-completed', payload.clientSocketId); + + await this.agentServiceRepository.storeOrgAgentDetails(storeOrgAgentData); + + this.notifyClientSocket('invitation-url-creation-started', payload.clientSocketId); + + // Create the legacy connection invitation + await this._createLegacyConnectionInvitation(payload.orgId, user, getOrganization.name); + + this.notifyClientSocket('invitation-url-creation-success', payload.clientSocketId); + } catch (error) { + this.handleError(error, payload.clientSocketId); + + if (agentProcess && agentProcess?.id) { + this.agentServiceRepository.removeOrgAgent(agentProcess?.id); + } + throw error; } + } /** * Create wallet - * @param payload + * @param payload * @returns wallet details */ async createWallet(payload: IWallet): Promise { try { - const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG); + const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( + CommonConstants.PLATFORM_ADMIN_ORG + ); - const getPlatformAgentEndPoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; - const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); + const getPlatformAgentEndPoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; + const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); - const { label } = payload; - const createTenantOptions = { - config: { label } - }; - - const tenantDetails = await this.commonService.httpPost( - `${getPlatformAgentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`, - createTenantOptions, - { headers: { 'authorization': getDcryptedToken } } - ); + const { label } = payload; + const createTenantOptions = { + config: { label } + }; - return tenantDetails; + const tenantDetails = await this.commonService.httpPost( + `${getPlatformAgentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`, + createTenantOptions, + { headers: { authorization: getDcryptedToken } } + ); + return tenantDetails; } catch (error) { this.logger.error(`error in create wallet : ${JSON.stringify(error)}`); throw new RpcException(error.response ? error.response : error); @@ -808,62 +885,62 @@ export class AgentServiceService { /** * Create did - * @param payload + * @param payload * @returns did and didDocument */ - async createDid(payload: IDidCreate, orgId: string, user: IUserRequestInterface): Promise { - try { + async createDid(payload: IDidCreate, orgId: string, user: IUserRequestInterface): Promise { + try { const agentDetails = await this.agentServiceRepository.getOrgAgentDetails(orgId); - + const getApiKey = await this.getOrgAgentApiKey(orgId); const getOrgAgentType = await this.agentServiceRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); let url; if (getOrgAgentType.agent === OrgAgentType.DEDICATED) { - url = `${agentDetails.agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; + url = `${agentDetails.agentEndPoint}${CommonConstants.URL_AGENT_WRITE_DID}`; } else if (getOrgAgentType.agent === OrgAgentType.SHARED) { - url = `${agentDetails.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${agentDetails.tenantId}`; + url = `${agentDetails.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${agentDetails.tenantId}`; } - const didDetails = await this.commonService.httpPost(url, payload, - { headers: { 'authorization': getApiKey } } - ); + const didDetails = await this.commonService.httpPost(url, payload, { headers: { authorization: getApiKey } }); return didDetails; - } catch (error) { - this.logger.error(`error in create did : ${JSON.stringify(error)}`); + this.logger.error(`error in create did : ${JSON.stringify(error)}`); - if (error?.response?.error?.message) { - throw new RpcException({ - statusCode: error?.response?.status, - error: error?.response?.error?.message - }); - } else { - throw new RpcException(error.response ? error.response : error); + if (error?.response?.error?.message) { + throw new RpcException({ + statusCode: error?.response?.status, + error: error?.response?.error?.message + }); + } else { + throw new RpcException(error.response ? error.response : error); + } } - } -} - /** + /** * @returns Secp256k1 key pair for polygon DID */ - async createSecp256k1KeyPair(orgId:string): Promise { - try { - const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( - CommonConstants.PLATFORM_ADMIN_ORG - ); + async createSecp256k1KeyPair(orgId: string): Promise { + try { + const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( + CommonConstants.PLATFORM_ADMIN_ORG + ); - const getPlatformAgentEndPoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; - const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); + const getPlatformAgentEndPoint = platformAdminSpinnedUp.org_agents[0].agentEndPoint; + const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); - const url = `${getPlatformAgentEndPoint}${CommonConstants.CREATE_POLYGON_SECP256k1_KEY}`; + const url = `${getPlatformAgentEndPoint}${CommonConstants.CREATE_POLYGON_SECP256k1_KEY}`; - const createKeyPairResponse = await this.commonService.httpPost(url, {}, { headers: { 'authorization': getDcryptedToken } }); - return createKeyPairResponse; - } catch (error) { - this.logger.error(`error in createSecp256k1KeyPair : ${JSON.stringify(error)}`); - throw new RpcException(error.response ? error.response : error); - } - } + const createKeyPairResponse = await this.commonService.httpPost( + url, + {}, + { headers: { authorization: getDcryptedToken } } + ); + return createKeyPairResponse; + } catch (error) { + this.logger.error(`error in createSecp256k1KeyPair : ${JSON.stringify(error)}`); + throw new RpcException(error.response ? error.response : error); + } + } private async getPlatformAdminAndNotify(clientSocketId: string | undefined): Promise { const socket = await this.createSocketInstance(); @@ -871,14 +948,16 @@ export class AgentServiceService { socket.emit('agent-spinup-process-initiated', { clientId: clientSocketId }); } - const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG); + const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent( + CommonConstants.PLATFORM_ADMIN_ORG + ); if (!platformAdminSpinnedUp) { this.logger.error(`Agent not able to spin-up`); - throw new BadRequestException( - ResponseMessages.agent.error.notAbleToSpinp, - { cause: new Error(), description: ResponseMessages.errorMessages.serverError } - ); + throw new BadRequestException(ResponseMessages.agent.error.notAbleToSpinp, { + cause: new Error(), + description: ResponseMessages.errorMessages.serverError + }); } return platformAdminSpinnedUp; @@ -886,15 +965,15 @@ export class AgentServiceService { /** * Create tenant on the agent - * @param payload - * @param ledgerIds - * @param platformAdminSpinnedUp + * @param payload + * @param ledgerIds + * @param platformAdminSpinnedUp * @returns Get tanant status */ - + // eslint-disable-next-line @typescript-eslint/no-explicit-any private async createTenantAndNotify(payload: ITenantDto, platformAdminSpinnedUp: IOrgAgentsResponse): Promise { - const WalletSetupPayload = {...payload}; + const WalletSetupPayload = { ...payload }; const socket = await this.createSocketInstance(); if (WalletSetupPayload.clientSocketId) { socket.emit('agent-spinup-process-initiated', { clientId: WalletSetupPayload.clientSocketId }); @@ -906,12 +985,15 @@ export class AgentServiceService { delete WalletSetupPayload.orgId; delete WalletSetupPayload.ledgerId; - const getDcryptedToken = await this.commonService.decryptPassword(platformAdminSpinnedUp?.org_agents[0].apiKey); - const walletResponseDetails = await this._createTenantWallet(walletLabel, platformAdminSpinnedUp.org_agents[0].agentEndPoint, getDcryptedToken); - if (!walletResponseDetails && !walletResponseDetails.id) { - throw new InternalServerErrorException('Error while creating the wallet'); - } + const walletResponseDetails = await this._createTenantWallet( + walletLabel, + platformAdminSpinnedUp.org_agents[0].agentEndPoint, + getDcryptedToken + ); + if (!walletResponseDetails && !walletResponseDetails.id) { + throw new InternalServerErrorException('Error while creating the wallet'); + } const didCreateOption = { didPayload: WalletSetupPayload, agentEndpoint: platformAdminSpinnedUp.org_agents[0].agentEndPoint, @@ -921,50 +1003,49 @@ export class AgentServiceService { const DIDCreationOption = await this._createDID(didCreateOption); if (!DIDCreationOption) { throw new InternalServerErrorException('Error while creating the wallet'); - } - - return {walletResponseDetails, DIDCreationOption}; + } + + return { walletResponseDetails, DIDCreationOption }; } -// + // - /** + /** * Create tenant wallet on the agent * @param createTenantWalletPayload * @returns Get tanant status */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - private async _createTenantWallet(label, endpoint, agentApiKey): Promise { //remove any - - - const createTenantOptions = { - config: { label } - }; - // Invoke an API request from the agent to create multi-tenant agent - const tenantDetails = await this.commonService.httpPost( - `${endpoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`, - createTenantOptions, - { headers: { authorization: agentApiKey } } - ); - return tenantDetails; -} + // eslint-disable-next-line @typescript-eslint/no-explicit-any + private async _createTenantWallet(label, endpoint, agentApiKey): Promise { + //remove any + + const createTenantOptions = { + config: { label } + }; + // Invoke an API request from the agent to create multi-tenant agent + const tenantDetails = await this.commonService.httpPost( + `${endpoint}${CommonConstants.URL_SHAGENT_CREATE_TENANT}`, + createTenantOptions, + { headers: { authorization: agentApiKey } } + ); + return tenantDetails; + } - /** + /** * Create tenant wallet on the agent * @param _createDID * @returns Get tanant status */ - private async _createDID(didCreateOption): Promise { - - const {didPayload, agentEndpoint, apiKey, tenantId} = didCreateOption; - // Invoke an API request from the agent to create multi-tenant agent - const didDetails = await this.commonService.httpPost( - `${agentEndpoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${tenantId}`, - didPayload, - { headers: { authorization: apiKey } } - ); - return didDetails; -} + private async _createDID(didCreateOption): Promise { + const { didPayload, agentEndpoint, apiKey, tenantId } = didCreateOption; + // Invoke an API request from the agent to create multi-tenant agent + const didDetails = await this.commonService.httpPost( + `${agentEndpoint}${CommonConstants.URL_SHAGENT_CREATE_DID}${tenantId}`, + didPayload, + { headers: { authorization: apiKey } } + ); + return didDetails; + } private async createSocketInstance(): Promise { return io(`${process.env.SOCKET_HOST}`, { reconnection: true, @@ -997,7 +1078,6 @@ export class AgentServiceService { let schemaResponse; if (OrgAgentType.DEDICATED === payload.agentType) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_CREATE_SCHEMA}`; const schemaPayload = { attributes: payload.attributes, @@ -1005,31 +1085,34 @@ export class AgentServiceService { name: payload.name, issuerId: payload.issuerId }; - schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': getApiKey } }) + schemaResponse = await this.commonService + .httpPost(url, schemaPayload, { headers: { authorization: getApiKey } }) .then(async (schema) => schema) - .catch(error => { - throw new InternalServerErrorException( - ResponseMessages.agent.error.agentDown, - { cause: new Error(), description: ResponseMessages.errorMessages.serverError } - ); + .catch((error) => { + throw new InternalServerErrorException(ResponseMessages.agent.error.agentDown, { + cause: new Error(), + description: ResponseMessages.errorMessages.serverError + }); }); - } else if (OrgAgentType.SHARED === payload.agentType) { - - const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_SCHEMA}`.replace('#', `${payload.tenantId}`); + const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_SCHEMA}`.replace( + '#', + `${payload.tenantId}` + ); const schemaPayload = { attributes: payload.payload.attributes, version: payload.payload.version, name: payload.payload.name, issuerId: payload.payload.issuerId }; - schemaResponse = await this.commonService.httpPost(url, schemaPayload, { headers: { 'authorization': getApiKey } }) + schemaResponse = await this.commonService + .httpPost(url, schemaPayload, { headers: { authorization: getApiKey } }) .then(async (schema) => schema) - .catch(error => { - throw new InternalServerErrorException( - ResponseMessages.agent.error.agentDown, - { cause: new Error(), description: ResponseMessages.errorMessages.serverError } - ); + .catch((error) => { + throw new InternalServerErrorException(ResponseMessages.agent.error.agentDown, { + cause: new Error(), + description: ResponseMessages.errorMessages.serverError + }); }); } return schemaResponse; @@ -1045,14 +1128,18 @@ export class AgentServiceService { const getApiKey = await this.getOrgAgentApiKey(payload.orgId); if (OrgAgentType.DEDICATED === payload.agentType) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_SCHEMA_BY_ID.replace('#', `${payload.schemaId}`)}`; - schemaResponse = await this.commonService.httpGet(url, payload.schemaId) - .then(async (schema) => schema); - + const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_SCHEMA_BY_ID.replace( + '#', + `${payload.schemaId}` + )}`; + schemaResponse = await this.commonService.httpGet(url, payload.schemaId).then(async (schema) => schema); } else if (OrgAgentType.SHARED === payload.agentType) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_SCHEMA}`.replace('@', `${payload.payload.schemaId}`).replace('#', `${payload.tenantId}`); + const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_SCHEMA}` + .replace('@', `${payload.payload.schemaId}`) + .replace('#', `${payload.tenantId}`); - schemaResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) + schemaResponse = await this.commonService + .httpGet(url, { headers: { authorization: getApiKey } }) .then(async (schema) => schema); } return schemaResponse; @@ -1068,7 +1155,6 @@ export class AgentServiceService { const getApiKey = await this.getOrgAgentApiKey(payload.orgId); if (OrgAgentType.DEDICATED === String(payload.agentType)) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_CREATE_CRED_DEF}`; const credDefPayload = { tag: payload.tag, @@ -1076,17 +1162,21 @@ export class AgentServiceService { issuerId: payload.issuerId }; - credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': getApiKey } }) + credDefResponse = await this.commonService + .httpPost(url, credDefPayload, { headers: { authorization: getApiKey } }) .then(async (credDef) => credDef); - } else if (OrgAgentType.SHARED === payload.agentType) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_CRED_DEF}`.replace('#', `${payload.tenantId}`); + const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_CREATE_CRED_DEF}`.replace( + '#', + `${payload.tenantId}` + ); const credDefPayload = { tag: payload.payload.tag, schemaId: payload.payload.schemaId, issuerId: payload.payload.issuerId }; - credDefResponse = await this.commonService.httpPost(url, credDefPayload, { headers: { 'authorization': getApiKey } }) + credDefResponse = await this.commonService + .httpPost(url, credDefPayload, { headers: { authorization: getApiKey } }) .then(async (credDef) => credDef); } @@ -1103,13 +1193,19 @@ export class AgentServiceService { const getApiKey = await this.getOrgAgentApiKey(payload.orgId); if (OrgAgentType.DEDICATED === payload.agentType) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_CRED_DEF_BY_ID.replace('#', `${payload.credentialDefinitionId}`)}`; - credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) + const url = `${payload.agentEndPoint}${CommonConstants.URL_SCHM_GET_CRED_DEF_BY_ID.replace( + '#', + `${payload.credentialDefinitionId}` + )}`; + credDefResponse = await this.commonService + .httpGet(url, { headers: { authorization: getApiKey } }) .then(async (credDef) => credDef); - } else if (OrgAgentType.SHARED === payload.agentType) { - const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CRED_DEF}`.replace('@', `${payload.payload.credentialDefinitionId}`).replace('#', `${payload.tenantId}`); - credDefResponse = await this.commonService.httpGet(url, { headers: { 'authorization': getApiKey } }) + const url = `${payload.agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CRED_DEF}` + .replace('@', `${payload.payload.credentialDefinitionId}`) + .replace('#', `${payload.tenantId}`); + credDefResponse = await this.commonService + .httpGet(url, { headers: { authorization: getApiKey } }) .then(async (credDef) => credDef); } return credDefResponse; @@ -1119,13 +1215,16 @@ export class AgentServiceService { } } - async createLegacyConnectionInvitation(connectionPayload: IConnectionDetails, url: string, orgId: string): Promise { + async createLegacyConnectionInvitation( + connectionPayload: IConnectionDetails, + url: string, + orgId: string + ): Promise { try { - const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpPost(url, connectionPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, connectionPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return data; } catch (error) { @@ -1138,8 +1237,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpPost(url, issueData, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, issueData, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return data; } catch (error) { this.logger.error(`Error in sendCredentialCreateOffer in agent service : ${JSON.stringify(error)}`); @@ -1149,8 +1248,8 @@ export class AgentServiceService { async getProofPresentations(url: string, apiKey: string): Promise { try { const getProofPresentationsData = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) - .then(async response => response); + .httpGet(url, { headers: { authorization: apiKey } }) + .then(async (response) => response); return getProofPresentationsData; } catch (error) { @@ -1162,8 +1261,8 @@ export class AgentServiceService { async getIssueCredentials(url: string, apiKey: string): Promise { try { const data = await this.commonService - .httpGet(url, { headers: { 'authorization': apiKey } }) - .then(async response => response); + .httpGet(url, { headers: { authorization: apiKey } }) + .then(async (response) => response); return data; } catch (error) { this.logger.error(`Error in getIssueCredentials in agent service : ${JSON.stringify(error)}`); @@ -1175,9 +1274,9 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const getProofPresentationById = await this.commonService - .httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async response => response) - .catch(error => this.handleAgentSpinupStatusErrors(error)); + .httpGet(url, { headers: { authorization: getApiKey } }) + .then(async (response) => response) + .catch((error) => this.handleAgentSpinupStatusErrors(error)); return getProofPresentationById; } catch (error) { @@ -1190,8 +1289,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpGet(url, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return data; } catch (error) { this.logger.error(`Error in getIssueCredentialsbyCredentialRecordId in agent service : ${JSON.stringify(error)}`); @@ -1199,12 +1298,16 @@ export class AgentServiceService { } } - async sendProofRequest(proofRequestPayload: ISendProofRequestPayload, url: string, orgId: string): Promise { + async sendProofRequest( + proofRequestPayload: ISendProofRequestPayload, + url: string, + orgId: string + ): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const sendProofRequest = await this.commonService - .httpPost(url, proofRequestPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, proofRequestPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return sendProofRequest; } catch (error) { this.logger.error(`Error in send proof request in agent service : ${JSON.stringify(error)}`); @@ -1216,9 +1319,9 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const verifyPresentation = await this.commonService - .httpPost(url, '', { headers: { 'authorization': getApiKey } }) - .then(async response => response) - .catch(error => this.handleAgentSpinupStatusErrors(error)); + .httpPost(url, '', { headers: { authorization: getApiKey } }) + .then(async (response) => response) + .catch((error) => this.handleAgentSpinupStatusErrors(error)); return verifyPresentation; } catch (error) { this.logger.error(`Error in verify proof presentation in agent service : ${JSON.stringify(error)}`); @@ -1230,8 +1333,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpGet(url, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return data; } catch (error) { this.logger.error(`Error in getConnections in agent service : ${JSON.stringify(error)}`); @@ -1240,59 +1343,57 @@ export class AgentServiceService { } async getConnectionsByconnectionId(url: string, orgId: string): Promise { - try { const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async response => response) - .catch(error => this.handleAgentSpinupStatusErrors(error)); + .httpGet(url, { headers: { authorization: getApiKey } }) + .then(async (response) => response) + .catch((error) => this.handleAgentSpinupStatusErrors(error)); return data; } catch (error) { this.logger.error(`Error in getConnectionsByconnectionId in agent service : ${JSON.stringify(error)}`); throw new RpcException(error.response ? error.response : error); } - } /** * Get agent health - * @param orgId + * @param orgId * @returns agent status */ async getAgentHealthDetails(orgId: string): Promise { try { - // Get organization agent details const orgAgentDetails: org_agents = await this.agentServiceRepository.getOrgAgentDetails(orgId); let agentApiKey; if (orgAgentDetails) { - agentApiKey = await this.getOrgAgentApiKey(orgId); + agentApiKey = await this.getOrgAgentApiKey(orgId); } if (!orgAgentDetails) { - throw new NotFoundException( - ResponseMessages.agent.error.agentNotExists, - { cause: new Error(), description: ResponseMessages.errorMessages.notFound } - ); + throw new NotFoundException(ResponseMessages.agent.error.agentNotExists, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); } if (!orgAgentDetails?.agentEndPoint) { - throw new NotFoundException( - ResponseMessages.agent.error.agentUrl, - { cause: new Error(), description: ResponseMessages.errorMessages.notFound } - ); + throw new NotFoundException(ResponseMessages.agent.error.agentUrl, { + cause: new Error(), + description: ResponseMessages.errorMessages.notFound + }); } // Invoke an API request from the agent to assess its current status const agentHealthData = await this.commonService - .httpGet(`${orgAgentDetails.agentEndPoint}${CommonConstants.URL_AGENT_STATUS}`, { headers: { 'authorization': agentApiKey } }) - .then(async response => response); + .httpGet(`${orgAgentDetails.agentEndPoint}${CommonConstants.URL_AGENT_STATUS}`, { + headers: { authorization: agentApiKey } + }) + .then(async (response) => response); return agentHealthData; - } catch (error) { this.logger.error(`Agent health details : ${JSON.stringify(error)}`); throw new RpcException(error.response ? error.response : error); @@ -1303,19 +1404,22 @@ export class AgentServiceService { try { const getLedgerConfigData = await this.agentServiceRepository.getLedgerConfigByOrgId(); return getLedgerConfigData; - } catch (error) { this.logger.error(`Error in send out of band proof request in agent service : ${JSON.stringify(error)}`); throw error; } } - async sendOutOfBandProofRequest(proofRequestPayload: ISendProofRequestPayload, url: string, orgId: string): Promise { + async sendOutOfBandProofRequest( + proofRequestPayload: ISendProofRequestPayload, + url: string, + orgId: string + ): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const sendProofRequest = await this.commonService - .httpPost(url, proofRequestPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, proofRequestPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return sendProofRequest; } catch (error) { this.logger.error(`Error in send out of band proof request in agent service : ${JSON.stringify(error)}`); @@ -1327,9 +1431,9 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const getVerifiedProofData = await this.commonService - .httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async response => response) - .catch(error => this.handleAgentSpinupStatusErrors(error)); + .httpGet(url, { headers: { authorization: getApiKey } }) + .then(async (response) => response) + .catch((error) => this.handleAgentSpinupStatusErrors(error)); return getVerifiedProofData; } catch (error) { @@ -1342,8 +1446,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const schemaRequest = await this.commonService - .httpPost(url, requestSchemaPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, requestSchemaPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return schemaRequest; } catch (error) { this.logger.error(`Error in schema endorsement request in agent service : ${JSON.stringify(error)}`); @@ -1355,11 +1459,13 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const credDefRequest = await this.commonService - .httpPost(url, requestSchemaPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, requestSchemaPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return credDefRequest; } catch (error) { - this.logger.error(`Error in credential-definition endorsement request in agent service : ${JSON.stringify(error)}`); + this.logger.error( + `Error in credential-definition endorsement request in agent service : ${JSON.stringify(error)}` + ); throw error; } } @@ -1368,8 +1474,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const signEndorsementTransaction = await this.commonService - .httpPost(url, signEndorsementPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, signEndorsementPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return signEndorsementTransaction; } catch (error) { @@ -1382,8 +1488,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const signEndorsementTransaction = await this.commonService - .httpPost(url, submitEndorsementPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, submitEndorsementPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return signEndorsementTransaction; } catch (error) { @@ -1392,12 +1498,16 @@ export class AgentServiceService { } } - async outOfBandCredentialOffer(outOfBandIssuancePayload: IOutOfBandCredentialOffer, url: string, orgId: string): Promise { + async outOfBandCredentialOffer( + outOfBandIssuancePayload: IOutOfBandCredentialOffer, + url: string, + orgId: string + ): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const sendOutOfbandCredentialOffer = await this.commonService - .httpPost(url, outOfBandIssuancePayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, outOfBandIssuancePayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return sendOutOfbandCredentialOffer; } catch (error) { this.logger.error(`Error in out-of-band credential in agent service : ${JSON.stringify(error)}`); @@ -1405,14 +1515,11 @@ export class AgentServiceService { } } - async deleteWallet( - url: string, - apiKey: string - ): Promise { + async deleteWallet(url: string, apiKey: string): Promise { try { const deleteWallet = await this.commonService - .httpDelete(url, { headers: { 'authorization': apiKey } }) - .then(async response => response); + .httpDelete(url, { headers: { authorization: apiKey } }) + .then(async (response) => response); return deleteWallet; } catch (error) { this.logger.error(`Error in delete wallet in agent service : ${JSON.stringify(error)}`); @@ -1424,8 +1531,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const receiveInvitationUrlRes = await this.commonService - .httpPost(url, receiveInvitationUrl, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, receiveInvitationUrl, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return receiveInvitationUrlRes; } catch (error) { this.logger.error(`Error in receive invitation in agent service : ${JSON.stringify(error)}`); @@ -1437,8 +1544,8 @@ export class AgentServiceService { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const receiveInvitationRes = await this.commonService - .httpPost(url, receiveInvitation, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, receiveInvitation, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return receiveInvitationRes; } catch (error) { this.logger.error(`Error in receive invitation in agent service : ${JSON.stringify(error)}`); @@ -1448,63 +1555,53 @@ export class AgentServiceService { async getOrgAgentApiKey(orgId: string): Promise { try { - let agentApiKey; - const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); - - const apiKey: string = await this.cacheService.get(CommonConstants.CACHE_APIKEY_KEY); - if (apiKey) { - const getDcryptedToken = await this.commonService.decryptPassword(apiKey); - return getDcryptedToken; - } - - const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); - if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) { - const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG); - - const [orgAgentData] = platformAdminSpinnedUp.org_agents; - const { apiKey } = orgAgentData; - if (!platformAdminSpinnedUp) { - throw new InternalServerErrorException('Agent not able to spin-up'); + const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId); + const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED); + const cacheKey = orgAgentApiKey?.orgAgentTypeId === orgAgentId ? CommonConstants.CACHE_SHARED_APIKEY_KEY : CommonConstants.CACHE_APIKEY_KEY; + + let apiKey = await this.cacheService.get(cacheKey); + if (!apiKey) { + if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) { + const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG); + if (!platformAdminSpinnedUp) { + throw new InternalServerErrorException('Agent not able to spin-up'); + } + apiKey = platformAdminSpinnedUp.org_agents[0]?.apiKey; + } else { + apiKey = orgAgentApiKey?.apiKey; + } + if (!apiKey) { + throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); + } + await this.cacheService.set(cacheKey, apiKey, 0); } - agentApiKey = apiKey; - - } else { - agentApiKey = orgAgentApiKey?.apiKey; - } - - if (!agentApiKey) { - throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist); - } - - await this.cacheService.set(CommonConstants.CACHE_APIKEY_KEY, agentApiKey, 0); - const getDcryptedToken = await this.commonService.decryptPassword(agentApiKey); - - return getDcryptedToken; - + const decryptedToken = await this.commonService.decryptPassword(apiKey); + return decryptedToken; } catch (error) { - this.logger.error(`Agent api key details : ${JSON.stringify(error)}`); - throw error; + this.logger.error(`Agent api key details : ${JSON.stringify(error)}`); + throw error; } - } +} + async handleAgentSpinupStatusErrors(error: string): Promise { if (error && Object.keys(error).length === 0) { - throw new InternalServerErrorException( - ResponseMessages.agent.error.agentDown, - { cause: new Error(), description: ResponseMessages.errorMessages.serverError } - ); + throw new InternalServerErrorException(ResponseMessages.agent.error.agentDown, { + cause: new Error(), + description: ResponseMessages.errorMessages.serverError + }); } else { throw error; } - } + } async sendQuestion(questionPayload: IQuestionPayload, url: string, orgId: string): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const sendQuestionRes = await this.commonService - .httpPost(url, questionPayload, { headers: { 'authorization': getApiKey } }) - .then(async response => response); + .httpPost(url, questionPayload, { headers: { authorization: getApiKey } }) + .then(async (response) => response); return sendQuestionRes; } catch (error) { this.logger.error(`Error in send question in agent service : ${JSON.stringify(error)}`); @@ -1513,35 +1610,28 @@ export class AgentServiceService { } async getQuestionAnswersRecord(url: string, orgId: string): Promise { - try { const getApiKey = await this.getOrgAgentApiKey(orgId); const data = await this.commonService - .httpGet(url, { headers: { 'authorization': getApiKey } }) - .then(async response => response) - .catch(error => this.handleAgentSpinupStatusErrors(error)); + .httpGet(url, { headers: { authorization: getApiKey } }) + .then(async (response) => response) + .catch((error) => this.handleAgentSpinupStatusErrors(error)); return data; } catch (error) { this.logger.error(`Error in getQuestionAnswersRecord in agent service : ${JSON.stringify(error)}`); throw new RpcException(error.response ? error.response : error); } - } private async tokenEncryption(token: string): Promise { try { - const encryptedToken = CryptoJS.AES.encrypt( - JSON.stringify(token), - process.env.CRYPTO_PRIVATE_KEY - ).toString(); + const encryptedToken = CryptoJS.AES.encrypt(JSON.stringify(token), process.env.CRYPTO_PRIVATE_KEY).toString(); return encryptedToken; - } catch (error) { throw error; } } - } diff --git a/libs/common/src/common.constant.ts b/libs/common/src/common.constant.ts index b93f0a0d7..83a0e78ee 100644 --- a/libs/common/src/common.constant.ts +++ b/libs/common/src/common.constant.ts @@ -313,7 +313,8 @@ export enum CommonConstants { ROLE = 'endorser', //CacheInfo -CACHE_APIKEY_KEY = "apiKey", +CACHE_SHARED_APIKEY_KEY = "dedicatedApiKey", +CACHE_APIKEY_KEY = "sharedApiKey", CACHE_TTL_SECONDS = 604800 } From fa4b3166697d1995ba7df8c1f06a40363be0d957 Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Tue, 19 Mar 2024 13:33:15 +0530 Subject: [PATCH 04/11] fix: solved the duplication code Signed-off-by: KulkarniShashank --- .../src/agent-service.service.ts | 83 +++++++------------ apps/connection/src/connection.service.ts | 35 ++++---- 2 files changed, 44 insertions(+), 74 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index b814a34a0..4675dd32c 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -634,24 +634,7 @@ export class AgentServiceService { cmd: 'create-connection' }; const payload = { orgId, user, label }; - return this.agentServiceProxy - .send(pattern, payload) - .pipe( - map((response) => ({ - response - })) - ) - .toPromise() - .catch((error) => { - this.logger.error(`catch: ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.statusCode, - error: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } catch (error) { this.logger.error(`error in create-connection in wallet provision : ${JSON.stringify(error)}`); } @@ -665,24 +648,7 @@ export class AgentServiceService { cmd: 'get-all-ledgers' }; const payload = {}; - return this.agentServiceProxy - .send(pattern, payload) - .pipe( - map((response) => ({ - response - })) - ) - .toPromise() - .catch((error) => { - this.logger.error(`catch: ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.statusCode, - error: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } catch (error) { this.logger.error(`error in while fetching all the ledger details : ${JSON.stringify(error)}`); } @@ -695,24 +661,7 @@ export class AgentServiceService { const pattern = { cmd: 'wallet-provisioning' }; - return this.agentServiceProxy - .send(pattern, payload) - .pipe( - map((response) => ({ - response - })) - ) - .toPromise() - .catch((error) => { - this.logger.error(`catch: ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.statusCode, - error: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } catch (error) { this.logger.error(`error in wallet provision : ${JSON.stringify(error)}`); throw error; @@ -1625,6 +1574,32 @@ export class AgentServiceService { } } + async natsCall(pattern: object, payload: object): Promise<{ + response: string; + }> { + try { + return this.agentServiceProxy + .send(pattern, payload) + .pipe( + map((response) => ( + { + response + })) + ).toPromise() + .catch(error => { + this.logger.error(`catch: ${JSON.stringify(error)}`); + throw new HttpException( + { + status: error.statusCode, + error: error.message + }, error.error); + }); + } catch (error) { + this.logger.error(`[natsCall] - error in nats call : ${JSON.stringify(error)}`); + throw error; + } + } + private async tokenEncryption(token: string): Promise { try { const encryptedToken = CryptoJS.AES.encrypt(JSON.stringify(token), process.env.CRYPTO_PRIVATE_KEY).toString(); diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index 18f72b391..712f5fed5 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -108,16 +108,7 @@ export class ConnectionService { return connectionDetailRecords; } catch (error) { this.logger.error(`[createLegacyConnectionInvitation] - error in connection invitation: ${error}`); - if (error && error?.status && error?.status?.message && error?.status?.message?.error) { - throw new RpcException({ - message: error?.status?.message?.error?.reason - ? error?.status?.message?.error?.reason - : error?.status?.message?.error, - statusCode: error?.status?.code - }); - } else { - throw new RpcException(error.response ? error.response : error); - } + this.handleError(error); } } @@ -383,16 +374,7 @@ export class ConnectionService { return record; } catch (error) { this.logger.error(`[sendQuestion] - error in get question answer record: ${error}`); - if (error && error?.status && error?.status?.message && error?.status?.message?.error) { - throw new RpcException({ - message: error?.status?.message?.error?.reason - ? error?.status?.message?.error?.reason - : error?.status?.message?.error, - statusCode: error?.status?.code - }); - } else { - throw new RpcException(error.response ? error.response : error); - } + this.handleError(error); } } @@ -763,4 +745,17 @@ export class ConnectionService { ); } } + + handleError(error): Promise { + if (error && error?.status && error?.status?.message && error?.status?.message?.error) { + throw new RpcException({ + message: error?.status?.message?.error?.reason + ? error?.status?.message?.error?.reason + : error?.status?.message?.error, + statusCode: error?.status?.code + }); + } else { + throw new RpcException(error.response ? error.response : error); + } + } } From b7386ec8a34fec4324070081c455ffce74b1291c Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Tue, 19 Mar 2024 16:41:08 +0530 Subject: [PATCH 05/11] fix: removed unnecessary import Signed-off-by: KulkarniShashank --- apps/agent-service/src/agent-service.service.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 4675dd32c..9c64a0566 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -46,10 +46,7 @@ import { IDidCreate, IWallet, ITenantRecord, - IPlatformAgent, - LedgerListResponse, - IOrgLedgers, - IStoreOrgAgent + LedgerListResponse } from './interface/agent-service.interface'; import { AgentSpinUpStatus, AgentType, DidMethod, Ledgers, OrgAgentType } from '@credebl/enum/enum'; import { AgentServiceRepository } from './repositories/agent-service.repository'; From ff0f419598d46794676bf312e6615ddbe88e8052 Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Tue, 19 Mar 2024 16:57:41 +0530 Subject: [PATCH 06/11] fix: removed duplicated code Signed-off-by: KulkarniShashank --- .../src/agent-service.controller.ts | 12 ++--- .../src/agent-service.service.ts | 52 ++++++++----------- 2 files changed, 26 insertions(+), 38 deletions(-) diff --git a/apps/agent-service/src/agent-service.controller.ts b/apps/agent-service/src/agent-service.controller.ts index be4c0b9b4..26d1c066b 100644 --- a/apps/agent-service/src/agent-service.controller.ts +++ b/apps/agent-service/src/agent-service.controller.ts @@ -1,10 +1,8 @@ import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; import { AgentServiceService } from './agent-service.service'; -import { IAgentStatus, IConnectionDetails, IUserRequestInterface, ISendProofRequestPayload, IAgentSpinUpSatus, IGetCredDefAgentRedirection, IGetSchemaAgentRedirection, IAgentSpinupDto, IIssuanceCreateOffer, ITenantCredDef, ITenantDto, ITenantSchema, IOutOfBandCredentialOffer, IProofPresentation, IAgentProofRequest, IPresentation, IDidCreate, IWallet, ITenantRecord } from './interface/agent-service.interface'; +import { IAgentStatus, IConnectionDetails, IUserRequestInterface, ISendProofRequestPayload, IAgentSpinUpSatus, IGetCredDefAgentRedirection, IGetSchemaAgentRedirection, IAgentSpinupDto, IIssuanceCreateOffer, ITenantCredDef, ITenantDto, ITenantSchema, IOutOfBandCredentialOffer, IAgentProofRequest, IDidCreate, IWallet, ITenantRecord } from './interface/agent-service.interface'; import { user } from '@prisma/client'; -import { IConnectionDetailsById } from 'apps/api-gateway/src/interfaces/IConnectionSearch.interface'; -import { IProofPresentationDetails } from '@credebl/common/interfaces/verification.interface'; import { InvitationMessage } from '@credebl/common/interfaces/agent-service.interface'; @Controller() @@ -99,7 +97,7 @@ export class AgentServiceController { //DONE @MessagePattern({ cmd: 'agent-get-proof-presentation-by-id' }) - async getProofPresentationById(payload: { url: string; orgId: string }): Promise { + async getProofPresentationById(payload: { url: string; orgId: string }): Promise { return this.agentServiceService.getProofPresentationById(payload.url, payload.orgId); } @@ -114,7 +112,7 @@ export class AgentServiceController { } //DONE @MessagePattern({ cmd: 'agent-verify-presentation' }) - async verifyPresentation(payload: { url: string; orgId: string }): Promise { + async verifyPresentation(payload: { url: string; orgId: string }): Promise { return this.agentServiceService.verifyPresentation(payload.url, payload.orgId); } @@ -125,7 +123,7 @@ export class AgentServiceController { } @MessagePattern({ cmd: 'agent-get-connection-details-by-connectionId' }) - async getConnectionsByconnectionId(payload: { url: string, orgId: string }): Promise { + async getConnectionsByconnectionId(payload: { url: string, orgId: string }): Promise { return this.agentServiceService.getConnectionsByconnectionId(payload.url, payload.orgId); } @@ -156,7 +154,7 @@ export class AgentServiceController { //DONE @MessagePattern({ cmd: 'get-agent-verified-proof-details' }) - async getVerifiedProofDetails(payload: { url: string; orgId: string }): Promise { + async getVerifiedProofDetails(payload: { url: string; orgId: string }): Promise { return this.agentServiceService.getVerifiedProofDetails(payload.url, payload.orgId); } diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 9c64a0566..319de2972 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -1216,14 +1216,9 @@ export class AgentServiceService { } } - async getProofPresentationById(url: string, orgId: string): Promise { + async getProofPresentationById(url: string, orgId: string): Promise { try { - const getApiKey = await this.getOrgAgentApiKey(orgId); - const getProofPresentationById = await this.commonService - .httpGet(url, { headers: { authorization: getApiKey } }) - .then(async (response) => response) - .catch((error) => this.handleAgentSpinupStatusErrors(error)); - + const getProofPresentationById = await this.agentCall(url, orgId); return getProofPresentationById; } catch (error) { this.logger.error(`Error in proof presentation by id in agent service : ${JSON.stringify(error)}`); @@ -1261,7 +1256,7 @@ export class AgentServiceService { } } - async verifyPresentation(url: string, orgId: string): Promise { + async verifyPresentation(url: string, orgId: string): Promise { try { const getApiKey = await this.getOrgAgentApiKey(orgId); const verifyPresentation = await this.commonService @@ -1288,15 +1283,10 @@ export class AgentServiceService { } } - async getConnectionsByconnectionId(url: string, orgId: string): Promise { + async getConnectionsByconnectionId(url: string, orgId: string): Promise { try { - const getApiKey = await this.getOrgAgentApiKey(orgId); - const data = await this.commonService - .httpGet(url, { headers: { authorization: getApiKey } }) - .then(async (response) => response) - .catch((error) => this.handleAgentSpinupStatusErrors(error)); - - return data; + const getConnectionsByconnectionId = await this.agentCall(url, orgId); + return getConnectionsByconnectionId; } catch (error) { this.logger.error(`Error in getConnectionsByconnectionId in agent service : ${JSON.stringify(error)}`); throw new RpcException(error.response ? error.response : error); @@ -1373,15 +1363,10 @@ export class AgentServiceService { } } - async getVerifiedProofDetails(url: string, orgId: string): Promise { + async getVerifiedProofDetails(url: string, orgId: string): Promise { try { - const getApiKey = await this.getOrgAgentApiKey(orgId); - const getVerifiedProofData = await this.commonService - .httpGet(url, { headers: { authorization: getApiKey } }) - .then(async (response) => response) - .catch((error) => this.handleAgentSpinupStatusErrors(error)); - - return getVerifiedProofData; + const getVerifiedProofDetails = await this.agentCall(url, orgId); + return getVerifiedProofDetails; } catch (error) { this.logger.error(`Error in get verified proof details in agent service : ${JSON.stringify(error)}`); throw new RpcException(error.response ? error.response : error); @@ -1557,18 +1542,23 @@ export class AgentServiceService { async getQuestionAnswersRecord(url: string, orgId: string): Promise { try { - const getApiKey = await this.getOrgAgentApiKey(orgId); + const getQuestionAnswersRecord = await this.agentCall(url, orgId); + return getQuestionAnswersRecord; + } catch (error) { + this.logger.error(`Error in getQuestionAnswersRecord in agent service : ${JSON.stringify(error)}`); + throw new RpcException(error.response ? error.response : error); + } + } - const data = await this.commonService + async agentCall(url: string, orgId: string): Promise { + const getApiKey = await this.getOrgAgentApiKey(orgId); + + const data = await this.commonService .httpGet(url, { headers: { authorization: getApiKey } }) .then(async (response) => response) .catch((error) => this.handleAgentSpinupStatusErrors(error)); - return data; - } catch (error) { - this.logger.error(`Error in getQuestionAnswersRecord in agent service : ${JSON.stringify(error)}`); - throw new RpcException(error.response ? error.response : error); - } + return data; } async natsCall(pattern: object, payload: object): Promise<{ From 9f88539e47d223d71a3cad5cd36b008bf54db190 Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Tue, 19 Mar 2024 18:03:30 +0530 Subject: [PATCH 07/11] fix: removed duplicated code Signed-off-by: KulkarniShashank --- apps/connection/src/connection.service.ts | 276 +++++++++------------- 1 file changed, 112 insertions(+), 164 deletions(-) diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index 712f5fed5..41ad7b317 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -23,7 +23,6 @@ import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { IConnectionList, ICreateConnectionUrl } from '@credebl/common/interfaces/connection.interface'; import { IConnectionDetailsById } from 'apps/api-gateway/src/interfaces/IConnectionSearch.interface'; import { IQuestionPayload } from './interfaces/question-answer.interfaces'; -import { InvitationMessage } from '@credebl/common/interfaces/agent-service.interface'; @Injectable() export class ConnectionService { @@ -74,18 +73,18 @@ export class ConnectionService { goalCode: goalCode || undefined, handshake: handshake || undefined, handshakeProtocols: handshakeProtocols || undefined, - recipientKey:recipientKey || undefined + recipientKey: recipientKey || undefined }; const orgAgentType = await this.connectionRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); const url = await this.getAgentUrl(orgAgentType, agentEndPoint, agentDetails?.tenantId); const createConnectionInvitation = await this._createConnectionInvitation(connectionPayload, url, orgId); - const connectionInvitationUrl: string = createConnectionInvitation?.message?.invitationUrl; - const shortenedUrl: string = await this.storeConnectionObjectAndReturnUrl( + const connectionInvitationUrl = createConnectionInvitation?.response?.invitationUrl; + const shortenedUrl = await this.storeConnectionObjectAndReturnUrl( connectionInvitationUrl, connectionPayload.multiUseInvitation ); - const recipientsKey = createConnectionInvitation?.message?.recipientKey || recipientKey; + const recipientsKey = createConnectionInvitation?.response?.recipientKey || recipientKey; const saveConnectionDetails = await this.connectionRepository.saveAgentConnectionInvitations( shortenedUrl, agentId, @@ -102,8 +101,8 @@ export class ConnectionService { createdBy: saveConnectionDetails.createdBy, lastChangedDateTime: saveConnectionDetails.lastChangedDateTime, lastChangedBy: saveConnectionDetails.lastChangedBy, - recordId: createConnectionInvitation.message.outOfBandRecord.id, - recipientKey:saveConnectionDetails.recipientKey + recordId: createConnectionInvitation.response.outOfBandRecord.id, + recipientKey: saveConnectionDetails.recipientKey }; return connectionDetailRecords; } catch (error) { @@ -136,15 +135,16 @@ export class ConnectionService { connectionPayload: object, url: string, orgId: string - ): Promise { + ): Promise<{ + response; + }> { //nats call in agent-service to create an invitation url const pattern = { cmd: 'agent-create-connection-legacy-invitation' }; const payload = { connectionPayload, url, orgId }; try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const message = await this.connectionServiceProxy.send(pattern, payload).toPromise(); - return { message }; + + return this.natsCall(pattern, payload); } catch (error) { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( @@ -250,35 +250,49 @@ export class ConnectionService { throw new NotFoundException(ResponseMessages.issuance.error.agentEndPointNotFound); } - let url: string; - if (orgAgentType === OrgAgentType.DEDICATED) { - url = `${agentEndPoint}${CommonConstants.URL_CONN_GET_CONNECTIONS}`; - } else if (orgAgentType === OrgAgentType.SHARED) { - url = `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CREATEED_INVITATIONS}`.replace( - '#', - agentDetails.tenantId - ); - } else { - throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); - } - - //Create the dynamic URL for Search Criteria - const criteriaParams = []; - if (alias) { criteriaParams.push(`alias=${alias}`); } - if (myDid) { criteriaParams.push(`myDid=${myDid}`); } - if (outOfBandId) { criteriaParams.push(`outOfBandId=${outOfBandId}`); } - if (state) { criteriaParams.push(`state=${state}`); } - if (theirDid) { criteriaParams.push(`theirDid=${theirDid}`); } - if (theirLabel) { criteriaParams.push(`theirLabel=${theirLabel}`); } - - if (0 < criteriaParams.length) { - url += `?${criteriaParams.join('&')}`; - } + let url: string; + if (orgAgentType === OrgAgentType.DEDICATED) { + url = `${agentEndPoint}${CommonConstants.URL_CONN_GET_CONNECTIONS}`; + } else if (orgAgentType === OrgAgentType.SHARED) { + url = `${agentEndPoint}${CommonConstants.URL_SHAGENT_GET_CREATEED_INVITATIONS}`.replace( + '#', + agentDetails.tenantId + ); + } else { + throw new NotFoundException(ResponseMessages.connection.error.agentUrlNotFound); + } + + //Create the dynamic URL for Search Criteria + const criteriaParams = []; + if (alias) { + criteriaParams.push(`alias=${alias}`); + } + if (myDid) { + criteriaParams.push(`myDid=${myDid}`); + } + if (outOfBandId) { + criteriaParams.push(`outOfBandId=${outOfBandId}`); + } + if (state) { + criteriaParams.push(`state=${state}`); + } + if (theirDid) { + criteriaParams.push(`theirDid=${theirDid}`); + } + if (theirLabel) { + criteriaParams.push(`theirLabel=${theirLabel}`); + } + + if (0 < criteriaParams.length) { + url += `?${criteriaParams.join('&')}`; + } const connectionResponse = await this._getAllConnections(url, orgId); return connectionResponse.response; } catch (error) { - this.logger.error(`[getConnectionsFromAgent] [NATS call]- error in fetch connections details : ${JSON.stringify(error)}`); + this.logger.error( + `[getConnectionsFromAgent] [NATS call]- error in fetch connections details : ${JSON.stringify(error)}` + ); throw new RpcException(error.response ? error.response : error); } @@ -293,24 +307,7 @@ export class ConnectionService { try { const pattern = { cmd: 'agent-get-all-connections' }; const payload = { url, orgId }; - return this.connectionServiceProxy - .send(pattern, payload) - .pipe( - map((response) => ({ - response - })) - ) - .toPromise() - .catch((error) => { - this.logger.error(`catch: ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.statusCode, - error: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } catch (error) { this.logger.error( `[_getAllConnections] [NATS call]- error in fetch connections details : ${JSON.stringify(error)}` @@ -323,7 +320,6 @@ export class ConnectionService { try { const agentDetails = await this.connectionRepository.getAgentEndPoint(orgId); const orgAgentType = await this.connectionRepository.getOrgAgentType(agentDetails?.orgAgentTypeId); - // const platformConfig: platform_config = await this.connectionRepository.getPlatformConfigDetails(); const { agentEndPoint } = agentDetails; if (!agentDetails) { @@ -342,7 +338,7 @@ export class ConnectionService { } const createConnectionInvitation = await this._getConnectionsByConnectionId(url, orgId); - return createConnectionInvitation; + return createConnectionInvitation?.response; } catch (error) { this.logger.error(`[getConnectionsById] - error in get connections : ${JSON.stringify(error)}`); @@ -378,50 +374,24 @@ export class ConnectionService { } } - async _getConnectionsByConnectionId(url: string, orgId: string): Promise { + async _getConnectionsByConnectionId( + url: string, + orgId: string + ): Promise<{ + response; + }> { //nats call in agent service for fetch connection details const pattern = { cmd: 'agent-get-connection-details-by-connectionId' }; const payload = { url, orgId }; - return this.connectionServiceProxy - .send(pattern, payload) - .toPromise() - .catch((error) => { - this.logger.error( - `[_getConnectionsByConnectionId] [NATS call]- error in fetch connections : ${JSON.stringify(error)}` - ); - throw new HttpException( - { - status: error.statusCode, - error: error.error?.message?.error ? error.error?.message?.error : error.error, - message: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } async _getQuestionAnswersRecord(url: string, orgId: string): Promise { const pattern = { cmd: 'agent-get-question-answer-record' }; const payload = { url, orgId }; - return this.connectionServiceProxy - .send(pattern, payload) - .toPromise() - .catch((error) => { - this.logger.error( - `[_getQuestionAnswersRecord] [NATS call]- error in fetch connections : ${JSON.stringify(error)}` - ); - throw new HttpException( - { - status: error.statusCode, - error: error.error?.message?.error ? error.error?.message?.error : error.error, - message: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } - /** * Description: Fetch agent url * @param referenceId @@ -492,14 +462,14 @@ export class ConnectionService { } } - async _getOrgAgentApiKey(orgId: string): Promise { + async _getOrgAgentApiKey(orgId: string): Promise<{ + response: string; + }> { const pattern = { cmd: 'get-org-agent-api-key' }; const payload = { orgId }; try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const message = await this.connectionServiceProxy.send(pattern, payload).toPromise(); - return message; + return this.natsCall(pattern, payload); } catch (error) { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( @@ -539,7 +509,7 @@ export class ConnectionService { } const createConnectionInvitation = await this._receiveInvitationUrl(url, orgId, receiveInvitationUrl); - return createConnectionInvitation; + return createConnectionInvitation.response; } catch (error) { this.logger.error(`[receiveInvitationUrl] - error in receive invitation url : ${JSON.stringify(error)}`); @@ -559,25 +529,12 @@ export class ConnectionService { url: string, orgId: string, receiveInvitationUrl: IReceiveInvitationUrl - ): Promise { + ): Promise<{ + response; + }> { const pattern = { cmd: 'agent-receive-invitation-url' }; const payload = { url, orgId, receiveInvitationUrl }; - return this.connectionServiceProxy - .send(pattern, payload) - .toPromise() - .catch((error) => { - this.logger.error( - `[_receiveInvitationUrl] [NATS call]- error in receive invitation url : ${JSON.stringify(error)}` - ); - throw new HttpException( - { - status: error.statusCode, - error: error.error?.message?.error ? error.error?.message?.error : error.error, - message: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } async receiveInvitation( @@ -604,7 +561,7 @@ export class ConnectionService { } const createConnectionInvitation = await this._receiveInvitation(url, orgId, receiveInvitation); - return createConnectionInvitation; + return createConnectionInvitation?.response; } catch (error) { this.logger.error(`[receiveInvitation] - error in receive invitation : ${JSON.stringify(error)}`); @@ -624,43 +581,18 @@ export class ConnectionService { url: string, orgId: string, receiveInvitation: IReceiveInvitation - ): Promise { + ): Promise<{ + response; + }> { const pattern = { cmd: 'agent-receive-invitation' }; const payload = { url, orgId, receiveInvitation }; - return this.connectionServiceProxy - .send(pattern, payload) - .toPromise() - .catch((error) => { - this.logger.error(`[_receiveInvitation] [NATS call]- error in receive invitation : ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.statusCode, - error: error.error?.message?.error ? error.error?.message?.error : error.error, - message: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } async _sendQuestion(questionPayload: IQuestionPayload, url: string, orgId: string): Promise { const pattern = { cmd: 'agent-send-question' }; const payload = { questionPayload, url, orgId }; - - return this.connectionServiceProxy - .send(pattern, payload) - .toPromise() - .catch((error) => { - this.logger.error(`[_sendQuestion] [NATS call]- error in send question : ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.statusCode, - error: error.error?.message?.error ? error.error?.message?.error : error.error, - message: error.message - }, - error.error - ); - }); + return this.natsCall(pattern, payload); } async sendQuestion(payload: IQuestionPayload): Promise { @@ -689,7 +621,7 @@ export class ConnectionService { agentDetails?.tenantId, connectionId ); - + const createQuestion = await this._sendQuestion(questionPayload, url, orgId); return createQuestion; } catch (error) { @@ -707,42 +639,58 @@ export class ConnectionService { } } - async storeConnectionObjectAndReturnUrl(connectionInvitationUrl: string, persistent: boolean): Promise { + async storeConnectionObjectAndReturnUrl( + connectionInvitationUrl: string, + persistent: boolean + ): Promise { const storeObj = connectionInvitationUrl; //nats call in agent-service to create an invitation url const pattern = { cmd: 'store-object-return-url' }; const payload = { persistent, storeObj }; try { - const message = await this.connectionServiceProxy - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .send(pattern, payload) + const message = await this.natsCall(pattern, payload); + return message.response; + } catch (error) { + this.logger.error(`catch: ${JSON.stringify(error)}`); + throw new HttpException( + { + status: error.status, + error: error.message + }, + error.status + ); + } + } + + async natsCall( + pattern: object, + payload: object + ): Promise<{ + response: string; + }> { + try { + return this.connectionServiceProxy + .send(pattern, payload) + .pipe( + map((response) => ({ + response + })) + ) .toPromise() .catch((error) => { - this.logger.error( - `[storeConnectionObjectAndReturnUrl] [NATS call]- error in storing object and returning url : ${JSON.stringify( - error - )}` - ); + this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( { status: error.statusCode, - error: error.error?.message?.error ? error.error?.message?.error : error.error, - message: error.message + error: error.message }, error.error ); }); - return message; } catch (error) { - this.logger.error(`catch: ${JSON.stringify(error)}`); - throw new HttpException( - { - status: error.status, - error: error.message - }, - error.status - ); + this.logger.error(`[natsCall] - error in nats call : ${JSON.stringify(error)}`); + throw error; } } From 781bdc1e6afda71e33c5a4d1cb342c720a8f537c Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Tue, 19 Mar 2024 18:49:48 +0530 Subject: [PATCH 08/11] fix: removed duplicated code Signed-off-by: KulkarniShashank --- apps/connection/src/connection.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index 41ad7b317..f8984b778 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -689,7 +689,7 @@ export class ConnectionService { ); }); } catch (error) { - this.logger.error(`[natsCall] - error in nats call : ${JSON.stringify(error)}`); + this.logger.error(`[ConnectionService natsCall] - error in nats call : ${JSON.stringify(error)}`); throw error; } } From d5588c7d3e7eb04123ba0dcfe8dd6e11cee8cdca Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Wed, 20 Mar 2024 12:44:59 +0530 Subject: [PATCH 09/11] fix: solved the sonar lint issues Signed-off-by: KulkarniShashank --- apps/agent-service/src/agent-service.service.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/agent-service/src/agent-service.service.ts b/apps/agent-service/src/agent-service.service.ts index 319de2972..07b0cc963 100644 --- a/apps/agent-service/src/agent-service.service.ts +++ b/apps/agent-service/src/agent-service.service.ts @@ -631,7 +631,7 @@ export class AgentServiceService { cmd: 'create-connection' }; const payload = { orgId, user, label }; - return this.natsCall(pattern, payload); + return await this.natsCall(pattern, payload); } catch (error) { this.logger.error(`error in create-connection in wallet provision : ${JSON.stringify(error)}`); } @@ -645,7 +645,7 @@ export class AgentServiceService { cmd: 'get-all-ledgers' }; const payload = {}; - return this.natsCall(pattern, payload); + return await this.natsCall(pattern, payload); } catch (error) { this.logger.error(`error in while fetching all the ledger details : ${JSON.stringify(error)}`); } @@ -658,7 +658,7 @@ export class AgentServiceService { const pattern = { cmd: 'wallet-provisioning' }; - return this.natsCall(pattern, payload); + return await this.natsCall(pattern, payload); } catch (error) { this.logger.error(`error in wallet provision : ${JSON.stringify(error)}`); throw error; From 3078b86607548b7de43a44da2d8f52e34f0b76a2 Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Wed, 20 Mar 2024 12:54:55 +0530 Subject: [PATCH 10/11] fix: solved the sonar lint issues Signed-off-by: KulkarniShashank --- apps/connection/src/connection.service.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/connection/src/connection.service.ts b/apps/connection/src/connection.service.ts index f8984b778..a2acdda52 100644 --- a/apps/connection/src/connection.service.ts +++ b/apps/connection/src/connection.service.ts @@ -144,7 +144,7 @@ export class ConnectionService { try { - return this.natsCall(pattern, payload); + return await this.natsCall(pattern, payload); } catch (error) { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( @@ -307,7 +307,7 @@ export class ConnectionService { try { const pattern = { cmd: 'agent-get-all-connections' }; const payload = { url, orgId }; - return this.natsCall(pattern, payload); + return await this.natsCall(pattern, payload); } catch (error) { this.logger.error( `[_getAllConnections] [NATS call]- error in fetch connections details : ${JSON.stringify(error)}` @@ -469,7 +469,7 @@ export class ConnectionService { const payload = { orgId }; try { - return this.natsCall(pattern, payload); + return await this.natsCall(pattern, payload); } catch (error) { this.logger.error(`catch: ${JSON.stringify(error)}`); throw new HttpException( @@ -671,7 +671,7 @@ export class ConnectionService { }> { try { return this.connectionServiceProxy - .send(pattern, payload) + .send(pattern, payload) .pipe( map((response) => ({ response From 613c860b8c8398f82e9cf7a2c8895ef2c4cdc454 Mon Sep 17 00:00:00 2001 From: KulkarniShashank Date: Wed, 20 Mar 2024 17:50:41 +0530 Subject: [PATCH 11/11] Solved verification interface issue Signed-off-by: KulkarniShashank --- apps/verification/src/interfaces/verification.interface.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/verification/src/interfaces/verification.interface.ts b/apps/verification/src/interfaces/verification.interface.ts index 1a8539585..b9172233e 100644 --- a/apps/verification/src/interfaces/verification.interface.ts +++ b/apps/verification/src/interfaces/verification.interface.ts @@ -176,7 +176,7 @@ export interface IProofRequestPayload { url: string; apiKey?: string; orgId?: string - proofRequestPayload: ISendProofRequestPayload; + proofRequestPayload: ISendProofRequestPayload | ISendPresentationExchangeProofRequestPayload; } interface IWebhookPresentationProof {