Skip to content

Commit

Permalink
MOSIP-31517 On demand changes move to release-1.2.0.1 (#1186)
Browse files Browse the repository at this point in the history
* MOSIP-31517 On demnad changes move to release

Signed-off-by: Neha Farheen <[email protected]>

* MOSIP-31517 On demnad changes move to release test case changes

Signed-off-by: Neha Farheen <[email protected]>

* Changes done

Signed-off-by: Neha Farheen <[email protected]>

---------

Signed-off-by: Neha Farheen <[email protected]>
Co-authored-by: Neha Farheen <[email protected]>
  • Loading branch information
Neha2365 and Neha Farheen authored Feb 9, 2024
1 parent 8c63446 commit f85b208
Show file tree
Hide file tree
Showing 9 changed files with 220 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,14 @@ public Tuple3<String, String, String> encryptData(byte[] data, String partnerCer
return Tuples.of(CryptoUtil.encodeBase64Url(encryptedData.getT1()), CryptoUtil.encodeBase64Url(encryptedData.getT2()), digestAsPlainText(certificateThumbprint));
}

public byte[] asymmetricEncryption(byte[] dataToEncrypt, String partnerCertificate)
throws IdAuthenticationBusinessException {
X509Certificate x509Certificate = getX509Certificate(partnerCertificate);
PublicKey publicKey = x509Certificate.getPublicKey();
byte[] encryptedData = cryptoCore.asymmetricEncrypt(publicKey, dataToEncrypt);
return encryptedData;
}

/**
* Encrypt.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package io.mosip.authentication.common.service.websub.impl;

import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.ON_DEMAND_TEMPLATE_EXTRACTION_TOPIC;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.mosip.authentication.common.service.entity.PartnerData;
import io.mosip.authentication.common.service.helper.WebSubHelper;
import io.mosip.authentication.common.service.repository.PartnerDataRepository;
import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
import io.mosip.authentication.core.indauth.dto.BaseRequestDTO;
import io.mosip.authentication.core.logger.IdaLogger;
import io.mosip.authentication.core.partner.dto.PartnerDTO;
import io.mosip.idrepository.core.security.IdRepoSecurityManager;
import io.mosip.kernel.core.logger.spi.Logger;
import io.mosip.kernel.core.util.DateUtils;
import io.mosip.kernel.core.websub.model.Event;
import io.mosip.kernel.core.websub.model.EventModel;

/**
* The Class OnDemandTemplateEventPublisher.
*
* @author Neha
*/
@Component
public class OndemandTemplateEventPublisher extends BaseWebSubEventsInitializer {

private static final String REQUEST_SIGNATURE = "requestSignature";

private static final String ENTITY_NAME = "entityName";

private static final String INDIVIDUAL_ID_TYPE = "individualIdType";

private static final String AUTH_PARTNER_ID = "authPartnerId";

private static final String INDIVIDUAL_ID = "individualId";

private static final String REQUESTDATETIME = "requestdatetime";

private static final String ERROR_MESSAGE = "error_message";

private static final String ERROR_CODE = "error_Code";

/** The Constant PUBLISHER_IDA. */
private static final String PUBLISHER_IDA = "IDA";

/** The Constant logger. */

private static final Logger logger = IdaLogger.getLogger(OndemandTemplateEventPublisher.class);


/** The on demand template extraction topic. */
@Value("${" + ON_DEMAND_TEMPLATE_EXTRACTION_TOPIC + "}")
private String onDemadTemplateExtractionTopic;

@Value("${mosip.ida.ondemand.template.extraction.partner.id}")
private String partnerId;

/** The web sub event publish helper. */
@Autowired
private WebSubHelper webSubHelper;

@Autowired
private IdAuthSecurityManager securityManager;

@Autowired
private PartnerDataRepository partnerDataRepo;

/**
* Do subscribe.
*/
@Override
protected void doSubscribe() {
// Nothing to do here since we are just publishing event for this topic
}

/**
* Try register topic partner service events.
*/
private void tryRegisterTopicOnDemandEvent() {
try {
logger.debug(IdAuthCommonConstants.SESSION_ID, "tryRegisterOnDemandEvent", "",
"Trying to register topic: " + onDemadTemplateExtractionTopic);
webSubHelper.registerTopic(onDemadTemplateExtractionTopic);
logger.info(IdAuthCommonConstants.SESSION_ID, "tryRegisterOnDemandEvent", "",
"Registered topic: " + onDemadTemplateExtractionTopic);
} catch (Exception e) {
logger.info(IdAuthCommonConstants.SESSION_ID, "tryRegisterOnDemandEvent", e.getClass().toString(),
"Error registering topic: " + onDemadTemplateExtractionTopic + "\n" + e.getMessage());
}
}

@Override
protected void doRegister() {
logger.info(IdAuthCommonConstants.SESSION_ID, "doRegister", this.getClass().getSimpleName(),
"On demand template event topic..");
tryRegisterTopicOnDemandEvent();
}

public void publishEvent(EventModel eventModel) {
webSubHelper.publishEvent(onDemadTemplateExtractionTopic, eventModel);
}

public void notify(BaseRequestDTO baserequestdto, String headerSignature, Optional<PartnerDTO> partner,
IdAuthenticationBusinessException e, Map<String, Object> metadata) {
try {
sendEvents(baserequestdto, headerSignature, partner, e, metadata);
} catch (Exception exception) {
logger.error(IdRepoSecurityManager.getUser(), "On demand template extraction", "notify",
exception.getMessage());
}
}

private void sendEvents(BaseRequestDTO baserequestdto, String headerSignature, Optional<PartnerDTO> partner,
IdAuthenticationBusinessException e, Map<String, Object> metadata) {
logger.info("Inside sendEvents ondemand extraction");
logger.info("Inside partner data to get certificate for ondemand extraction encryption");
Optional<PartnerData> partnerDataCert = partnerDataRepo.findByPartnerId(partnerId);
if (partnerDataCert.isEmpty()) {
logger.info("Partner is not configured for on demand extraction.");
} else {
Map<String, Object> eventData = new HashMap<>();
eventData.put(ERROR_CODE, e.getErrorCode());
eventData.put(ERROR_MESSAGE, e.getErrorText());
eventData.put(REQUESTDATETIME, DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime()));
eventData.put(INDIVIDUAL_ID,
encryptIndividualId(baserequestdto.getIndividualId(), partnerDataCert.get().getCertificateData()));
eventData.put(AUTH_PARTNER_ID, partner.get().getPartnerId());
eventData.put(INDIVIDUAL_ID_TYPE, baserequestdto.getIndividualIdType());
eventData.put(ENTITY_NAME, partner.get().getPartnerName());
eventData.put(REQUEST_SIGNATURE, headerSignature);
EventModel eventModel = createEventModel(onDemadTemplateExtractionTopic, eventData);
publishEvent(eventModel);
}
}

private EventModel createEventModel(String topic, Map<String, Object> eventData) {
EventModel model = new EventModel();
model.setPublisher(PUBLISHER_IDA);
String dateTime = DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime());
model.setPublishedOn(dateTime);
Event event = new Event();
event.setTimestamp(dateTime);
String eventId = UUID.randomUUID().toString();
event.setId(eventId);
event.setData(eventData);
model.setEvent(event);
model.setTopic(topic);
return model;
}

private byte[] encryptIndividualId(String id, String partnerCertificate) {
try {
logger.info("Inside the method of encryptIndividualId using partner certificate ");
return securityManager.asymmetricEncryption(id.getBytes(), partnerCertificate);
} catch (IdAuthenticationBusinessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ private IdAuthConfigKeyConstants() {
public static final String AUTH_TRANSACTION_STATUS_TOPIC = "ida-topic-auth-transaction-status";
public static final String AUTH_ANONYMOUS_PROFILE_TOPIC = "ida-topic-auth-anonymous-profile";
public static final String AUTH_FRAUD_ANALYSIS_TOPIC = "ida-topic-fraud-analysis";
public static final String ON_DEMAND_TEMPLATE_EXTRACTION_TOPIC = "ida-topic-on-demand-template-extraction";

public static final String IDA_MAX_CREDENTIAL_PULL_WINDOW_DAYS = "ida-max-credential-pull-window-days";
public static final String IDA_MAX_WEBSUB_MSG_PULL_WINDOW_DAYS = "ida-max-websub-messages-pull-window-days";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import io.mosip.authentication.common.service.websub.impl.AuthTransactionStatusEventPublisher;
import io.mosip.authentication.common.service.websub.impl.IdAuthFraudAnalysisEventPublisher;
import io.mosip.authentication.common.service.websub.impl.MasterDataUpdateEventInitializer;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.common.service.websub.impl.PartnerCACertEventInitializer;
import io.mosip.authentication.common.service.websub.impl.PartnerServiceEventsInitializer;
import io.mosip.authentication.core.util.IdTypeUtil;
Expand All @@ -71,6 +72,7 @@
import io.mosip.kernel.keymanager.hsm.health.HSMHealthCheck;
import io.mosip.kernel.keymanager.hsm.impl.KeyStoreImpl;
import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper;
import io.mosip.kernel.keymanagerservice.helper.PrivateKeyDecryptorHelper;
import io.mosip.kernel.keymanagerservice.helper.SessionKeyDecrytorHelper;
import io.mosip.kernel.keymanagerservice.service.impl.KeymanagerServiceImpl;
import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil;
Expand All @@ -82,7 +84,6 @@
import io.mosip.kernel.tokenidgenerator.generator.TokenIDGenerator;
import io.mosip.kernel.tokenidgenerator.service.impl.TokenIDGeneratorServiceImpl;
import io.mosip.kernel.zkcryptoservice.service.impl.ZKCryptoManagerServiceImpl;
import io.mosip.kernel.keymanagerservice.helper.PrivateKeyDecryptorHelper;

/**
* Spring-boot class for ID Authentication Application.
Expand Down Expand Up @@ -111,7 +112,7 @@
PartnerCACertEventServiceImpl.class, PartnerCACertEventInitializer.class,
IdAuthWebSubInitializer.class, AuthAnonymousEventPublisher.class, EnvUtil.class, KeyBindedTokenMatcherUtil.class,
HSMHealthCheck.class, PrivateKeyDecryptorHelper.class,
PasswordAuthServiceImpl.class, PasswordComparator.class })
PasswordAuthServiceImpl.class, PasswordComparator.class, OndemandTemplateEventPublisher.class })
@ComponentScan(basePackages = { "io.mosip.authentication.otp.service.*",
"io.mosip.kernel.core.logger.config", "${mosip.auth.adapter.impl.basepackage}" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = {
"io.mosip.idrepository.core.config.IdRepoDataSourceConfig.*" }))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
import io.mosip.authentication.common.service.validator.OTPRequestValidator;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.core.constant.AuditEvents;
import io.mosip.authentication.core.constant.AuditModules;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
Expand Down Expand Up @@ -90,6 +91,9 @@ public class OTPController {

@Autowired
private IdAuthSecurityManager securityManager;

@Autowired
private OndemandTemplateEventPublisher ondemandTemplateEventPublisher;

@InitBinder
private void initBinder(WebDataBinder binder) {
Expand Down Expand Up @@ -155,6 +159,10 @@ public OtpResponseDTO generateOTP(@Valid @RequestBody OtpRequestDTO otpRequestDt
throw authTransactionHelper.createDataValidationException(authTxnBuilder, e, requestWithMetadata);
} catch (IdAuthenticationBusinessException e) {
logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText());
if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(otpRequestDto, request.getHeader("signature"), partner, e,
otpRequestDto.getMetadata());
}
auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE , otpRequestDto.getTransactionID(),
IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), e);
authTransactionHelper.setAuthTransactionEntityMetadata(requestWithMetadata, authTxnBuilder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import io.mosip.authentication.common.service.websub.impl.AuthTransactionStatusEventPublisher;
import io.mosip.authentication.common.service.websub.impl.IdAuthFraudAnalysisEventPublisher;
import io.mosip.authentication.common.service.websub.impl.MasterDataUpdateEventInitializer;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.common.service.websub.impl.PartnerCACertEventInitializer;
import io.mosip.authentication.common.service.websub.impl.PartnerServiceEventsInitializer;
import io.mosip.authentication.core.util.DemoMatcherUtil;
Expand Down Expand Up @@ -94,7 +95,7 @@
import io.mosip.kernel.tokenidgenerator.service.impl.TokenIDGeneratorServiceImpl;
import io.mosip.kernel.zkcryptoservice.service.impl.ZKCryptoManagerServiceImpl;
import io.mosip.kernel.keymanager.hsm.health.HSMHealthCheck;
import io.mosip.kernel.keymanagerservice.helper.PrivateKeyDecryptorHelper;


/**
* Spring-boot class for ID Authentication Application.
Expand Down Expand Up @@ -125,7 +126,7 @@
AuthAnonymousProfileServiceImpl.class, AuthAnonymousEventPublisher.class, SessionKeyDecrytorHelper.class, ExternalRestHelperConfig.class, IdaRequestResponsConsumerUtil.class,
PartnerCACertEventServiceImpl.class, PartnerCACertEventInitializer.class, EnvUtil.class, KeyBindedTokenMatcherUtil.class,
HSMHealthCheck.class, TokenValidationHelper.class, VCSchemaProviderUtil.class, PrivateKeyDecryptorHelper.class,
PasswordAuthServiceImpl.class, PasswordComparator.class })
PasswordAuthServiceImpl.class, PasswordComparator.class, OndemandTemplateEventPublisher.class })
@ComponentScan(basePackages = { "io.mosip.authentication.service.*", "io.mosip.kernel.core.logger.config",
"io.mosip.authentication.common.service.config", "${mosip.auth.adapter.impl.basepackage}" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = {
"io.mosip.idrepository.core.config.IdRepoDataSourceConfig.*" }))
Expand All @@ -142,4 +143,4 @@ public static void main(String[] args) {
SpringApplication.run(IdAuthenticationApplication.class, args);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.mosip.authentication.common.service.util.AuthTypeUtil;
import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
import io.mosip.authentication.common.service.validator.AuthRequestValidator;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.core.constant.AuditEvents;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
Expand Down Expand Up @@ -88,6 +89,9 @@ public class AuthController {

@Autowired
private PartnerService partnerService;

@Autowired
private OndemandTemplateEventPublisher ondemandTemplateEventPublisher;


/**
Expand Down Expand Up @@ -157,8 +161,11 @@ public AuthResponseDTO authenticateIndividual(@Validated @RequestBody AuthReques
throw authTransactionHelper.createDataValidationException(authTxnBuilder, e, requestWithMetadata);
} catch (IdAuthenticationBusinessException e) {
mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(),
"authenticateApplication", e.getErrorCode() + " : " + e.getErrorText());

"authenticateApplication", e.getErrorCode() + " : " + e.getErrorText());
if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(authrequestdto, request.getHeader("signature"), partner, e,
authrequestdto.getMetadata());
}
auditHelper.auditExceptionForAuthRequestedModules(AuditEvents.AUTH_REQUEST_RESPONSE, authrequestdto, e);
IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWithMetadata, e);
e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, authrequestdto.getTransactionID());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.mosip.authentication.common.service.util.AuthTypeUtil;
import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
import io.mosip.authentication.common.service.validator.AuthRequestValidator;
import io.mosip.authentication.common.service.websub.impl.OndemandTemplateEventPublisher;
import io.mosip.authentication.core.constant.AuditEvents;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
Expand Down Expand Up @@ -98,6 +99,9 @@ public class KycAuthController {
/** The KycExchangeRequestValidator */
@Autowired
private KycExchangeRequestValidator kycExchangeValidator;

@Autowired
private OndemandTemplateEventPublisher ondemandTemplateEventPublisher;

/**
*
Expand Down Expand Up @@ -194,6 +198,10 @@ public EKycAuthResponseDTO processKyc(@Validated @RequestBody EkycAuthRequestDTO
mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "processEKyc",
e.getErrorTexts().isEmpty() ? "" : e.getErrorText());

if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(ekycAuthRequestDTO, request.getHeader("signature"), partner,
e, ekycAuthRequestDTO.getMetadata());
}
auditHelper.auditExceptionForAuthRequestedModules(AuditEvents.EKYC_REQUEST_RESPONSE, ekycAuthRequestDTO, e);
IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWrapperWithMetadata, e);
e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, ekycAuthRequestDTO.getTransactionID());
Expand Down Expand Up @@ -272,6 +280,10 @@ public KycAuthResponseDTO processKycAuth(@Validated @RequestBody KycAuthRequestD
mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "processKycAuth",
e.getErrorTexts().isEmpty() ? "" : e.getErrorText());

if (IdAuthenticationErrorConstants.ID_NOT_AVAILABLE.getErrorCode().equals(e.getErrorCode())) {
ondemandTemplateEventPublisher.notify(authRequestDTO, request.getHeader("signature"), partner, e,
authRequestDTO.getMetadata());
}
auditHelper.auditExceptionForAuthRequestedModules(AuditEvents.KYC_REQUEST_RESPONSE, authRequestDTO, e);
IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWrapperWithMetadata, e);
e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, authRequestDTO.getTransactionID());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public void processKycFailure1() throws IdAuthenticationBusinessException, IdAut
kycAuthController.processKyc(kycAuthReqDTO, errors, "1635497344579", "1635497344579", "1635497344579", new TestHttpServletRequest());
}

@Test(expected = IdAuthenticationAppException.class)
@Test
public void processKycFailure2() throws IdAuthenticationBusinessException, IdAuthenticationAppException,
IdAuthenticationDaoException, Exception {

Expand All @@ -293,6 +293,6 @@ public void processKycFailure2() throws IdAuthenticationBusinessException, IdAut
requestWithMetadata.setMetadata(new HashMap<>());
Mockito.when(kycFacade.authenticateIndividual(kycAuthReqDTO, true, "1635497344579", "1635497344579", requestWithMetadata)).thenThrow(new IdAuthenticationBusinessException());
Mockito.when(kycFacade.processEKycAuth(kycAuthReqDTO, authResponseDTO, "1635497344579", requestWithMetadata.getMetadata())).thenReturn(kycAuthResponseDTO);
kycAuthController.processKyc(kycAuthReqDTO, errors, "1635497344579", "1635497344579", "1635497344579", requestWithMetadata);
kycAuthController.processKyc(kycAuthReqDTO, errors, "1635497344579", "1635497344579", "1635497344579", new TestHttpServletRequest());
}
}

0 comments on commit f85b208

Please sign in to comment.