From ec11609bf31f2b3cc8da46bcdb22f9c17598269c Mon Sep 17 00:00:00 2001 From: RitikJain4108 <99730411+RitikJain4108@users.noreply.github.com> Date: Thu, 23 May 2024 20:57:41 +0530 Subject: [PATCH 1/9] [ES-558] Revoke issued handle credentials and publish an event (#1270) * update code to publish event Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * fix github build failure Signed-off-by: Ritik Jain (IN74108) --------- Signed-off-by: Ritik Jain (IN74108) Co-authored-by: Ritik Jain (IN74108) Signed-off-by: dhanendra06 --- .../IdChangeEventHandlerServiceImpl.java | 26 ++++++++++++++++--- .../impl/idevent/RemoveIdStatusEvent.java | 25 ++++++++++++++++++ .../constant/IdAuthConfigKeyConstants.java | 1 + .../KycAuthRequestValidatorTest.java | 2 +- .../VciExchangeRequestValidatorTest.java | 2 +- 5 files changed, 51 insertions(+), 5 deletions(-) create mode 100644 authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/RemoveIdStatusEvent.java diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java index d1b9a9077d6..1eaa5aad8af 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java @@ -1,5 +1,7 @@ package io.mosip.authentication.common.service.impl.idevent; +import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.REMOVE_ID_STATUS_TOPIC; + import java.time.LocalDateTime; import java.util.Map; import java.util.Optional; @@ -7,10 +9,12 @@ import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import io.mosip.authentication.common.service.entity.IdentityEntity; import io.mosip.authentication.common.service.helper.AuditHelper; +import io.mosip.authentication.common.service.helper.WebSubHelper; import io.mosip.authentication.common.service.repository.IdentityCacheRepository; import io.mosip.authentication.common.service.spi.idevent.CredentialStoreService; import io.mosip.authentication.core.constant.AuditEvents; @@ -75,6 +79,14 @@ static interface ConsumerWithBusinessException { @Autowired private CredentialStoreService credStorService; + + /** The web sub event publish helper. */ + @Autowired + private WebSubHelper webSubHelper; + + /** The remove id status topic. */ + @Value("${" + REMOVE_ID_STATUS_TOPIC + "}") + private String removeIdStatusTopic; /* (non-Javadoc) * @see io.mosip.authentication.core.spi.idevent.service.IdChangeEventHandlerService#handleIdEvent(java.util.List) @@ -183,11 +195,19 @@ private void handleRemoveId(EventModel eventModel) throws IdAuthenticationBusine Event event = eventModel.getEvent(); Map additionalData = event.getData(); String idHash = (String) additionalData.get(ID_HASH); - Optional identityEntityOpt = identityCacheRepo.findById(idHash); - if(identityEntityOpt.isPresent()) { - identityCacheRepo.delete(identityEntityOpt.get()); + if (idHash != null && !idHash.isEmpty()) { + identityCacheRepo.deleteById(idHash); + publishRemoveIdStatusEvent(idHash); } } + + public void publishRemoveIdStatusEvent(String idHash) { + RemoveIdStatusEvent removeIdStatusEvent = new RemoveIdStatusEvent(); + removeIdStatusEvent.setData(Map.of(ID_HASH, idHash)); + removeIdStatusEvent.setTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + webSubHelper.publishEvent(removeIdStatusTopic, + webSubHelper.createEventModel(removeIdStatusTopic, removeIdStatusEvent)); + } private void handleDeactivateId(EventModel eventModel) throws IdAuthenticationBusinessException { updateIdentityMetadata(eventModel); diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/RemoveIdStatusEvent.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/RemoveIdStatusEvent.java new file mode 100644 index 00000000000..d4b2f284f01 --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/RemoveIdStatusEvent.java @@ -0,0 +1,25 @@ +package io.mosip.authentication.common.service.impl.idevent; + +import java.util.Map; + +import io.mosip.authentication.common.service.websub.dto.EventInterface; +import lombok.Data; + +/** + * Instantiates a new remove id status event. + * + * @author Ritik Jain + */ +@Data +public class RemoveIdStatusEvent implements EventInterface { + + /** The id. */ + private String id; + + /** The timestamp. */ + private String timestamp; + + /** The data. */ + private Map data; + +} diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthConfigKeyConstants.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthConfigKeyConstants.java index d678bd80262..2f4fd4d118b 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthConfigKeyConstants.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthConfigKeyConstants.java @@ -135,6 +135,7 @@ private IdAuthConfigKeyConstants() { 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 AUTHENTICATION_ERROR_EVENTING_TOPIC = "ida-topic-authentication-error-eventing"; + public static final String REMOVE_ID_STATUS_TOPIC = "ida-topic-remove-id-status"; 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"; diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycAuthRequestValidatorTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycAuthRequestValidatorTest.java index c6fe2f1613d..2a4acc62655 100644 --- a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycAuthRequestValidatorTest.java +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycAuthRequestValidatorTest.java @@ -50,7 +50,7 @@ */ @RunWith(SpringRunner.class) @WebMvcTest -@ContextConfiguration(classes = { TestContext.class, WebApplicationContext.class }) +@ContextConfiguration(classes = { WebApplicationContext.class }) @Import(EnvUtil.class) @TestPropertySource(locations="classpath:application.properties") public class KycAuthRequestValidatorTest { diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/VciExchangeRequestValidatorTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/VciExchangeRequestValidatorTest.java index 0a69dd9d754..0b4a383ae55 100644 --- a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/VciExchangeRequestValidatorTest.java +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/VciExchangeRequestValidatorTest.java @@ -31,7 +31,7 @@ @RunWith(SpringRunner.class) @WebMvcTest -@ContextConfiguration(classes = { TestContext.class, WebApplicationContext.class }) +@ContextConfiguration(classes = { WebApplicationContext.class }) @Import(EnvUtil.class) @TestPropertySource(locations="classpath:application.properties") public class VciExchangeRequestValidatorTest { From 0b47aa52a024b5e3467fa253bf4c4231e55f3823 Mon Sep 17 00:00:00 2001 From: ase-101 Date: Fri, 24 May 2024 16:08:49 +0530 Subject: [PATCH 2/9] resolved the conflict for VCI Signed-off-by: dhanendra06 --- .../integration/service/IdaVCIssuancePluginImpl.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java index 90f4fbe82e4..afd43cdf1db 100644 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java +++ b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java @@ -132,18 +132,19 @@ public VCResult getVerifiableCredentialWithLinkedDataProof(VCReque requestEntity, new ParameterizedTypeReference>>() {}); if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { IdaResponseWrapper> responseWrapper = responseEntity.getBody(); - if (responseWrapper.getResponse() != null) { + if (responseWrapper != null && responseWrapper.getResponse() != null) + { VCResult vCResult = new VCResult(); vCResult.setCredential(responseWrapper.getResponse().getVerifiableCredentials()); vCResult.setFormat(vcRequestDto.getFormat()); return vCResult; } - log.error("Errors in response received from IDA VCI Exchange: {}", responseWrapper.getErrors()); + log.error("Errors in response received from IDA VCI Exchange: {}", responseWrapper.getErrors()); //NOSONAR responseWrapper is already evaluated to be not null throw new VCIExchangeException(CollectionUtils.isEmpty(responseWrapper.getErrors()) ? ErrorConstants.DATA_EXCHANGE_FAILED : responseWrapper.getErrors().get(0).getErrorCode()); } log.error("Error response received from IDA (VCI-exchange) with status : {}", responseEntity.getStatusCode()); - } catch (Exception e) { + } catch (VCIExchangeException e) { throw e; } catch (Exception e) { log.error("IDA Vci-exchange failed ", e); } throw new VCIExchangeException(); @@ -198,8 +199,8 @@ private byte[] b64Decode(String value) { //Converts an array of two-letter language codes to their corresponding ISO 639-2/T language codes. private List convertLangCodesToISO3LanguageCodes(String[] langCodes) { - if(langCodes == null || langCodes.length == 0) - return List.of("eng"); + if(langCodes == null || langCodes.length == 0 || (langCodes.length == 1 && langCodes[0].isEmpty())) + return List.of(); return Arrays.stream(langCodes) .map(langCode -> { try { From 43658d777927a99557c7dedc1d33cb97b62aa3de Mon Sep 17 00:00:00 2001 From: RitikJain4108 <99730411+RitikJain4108@users.noreply.github.com> Date: Tue, 28 May 2024 16:57:06 +0530 Subject: [PATCH 3/9] [ES-558] Revoke issued handle credentials and publish an event (#1274) * update code to publish event Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * fix github build failure Signed-off-by: Ritik Jain (IN74108) * registered topic Signed-off-by: Ritik Jain (IN74108) --------- Signed-off-by: Ritik Jain (IN74108) Co-authored-by: Ritik Jain (IN74108) Co-authored-by: 61074108 <61074108@5CD12778H4> Signed-off-by: dhanendra06 --- .../IdChangeEventHandlerServiceImpl.java | 22 +---- .../impl/RemoveIdStatusEventPublisher.java | 92 +++++++++++++++++++ .../InternalAuthWebSubInitializer.java | 6 ++ 3 files changed, 101 insertions(+), 19 deletions(-) create mode 100644 authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/websub/impl/RemoveIdStatusEventPublisher.java diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java index 1eaa5aad8af..c91749d4ccd 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java @@ -1,7 +1,5 @@ package io.mosip.authentication.common.service.impl.idevent; -import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.REMOVE_ID_STATUS_TOPIC; - import java.time.LocalDateTime; import java.util.Map; import java.util.Optional; @@ -9,14 +7,13 @@ import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import io.mosip.authentication.common.service.entity.IdentityEntity; import io.mosip.authentication.common.service.helper.AuditHelper; -import io.mosip.authentication.common.service.helper.WebSubHelper; import io.mosip.authentication.common.service.repository.IdentityCacheRepository; import io.mosip.authentication.common.service.spi.idevent.CredentialStoreService; +import io.mosip.authentication.common.service.websub.impl.RemoveIdStatusEventPublisher; import io.mosip.authentication.core.constant.AuditEvents; import io.mosip.authentication.core.constant.AuditModules; import io.mosip.authentication.core.constant.IdAuthCommonConstants; @@ -80,13 +77,8 @@ static interface ConsumerWithBusinessException { @Autowired private CredentialStoreService credStorService; - /** The web sub event publish helper. */ @Autowired - private WebSubHelper webSubHelper; - - /** The remove id status topic. */ - @Value("${" + REMOVE_ID_STATUS_TOPIC + "}") - private String removeIdStatusTopic; + private RemoveIdStatusEventPublisher removeIdStatusEventPublisher; /* (non-Javadoc) * @see io.mosip.authentication.core.spi.idevent.service.IdChangeEventHandlerService#handleIdEvent(java.util.List) @@ -197,17 +189,9 @@ private void handleRemoveId(EventModel eventModel) throws IdAuthenticationBusine String idHash = (String) additionalData.get(ID_HASH); if (idHash != null && !idHash.isEmpty()) { identityCacheRepo.deleteById(idHash); - publishRemoveIdStatusEvent(idHash); + removeIdStatusEventPublisher.publishRemoveIdStatusEvent(idHash); } } - - public void publishRemoveIdStatusEvent(String idHash) { - RemoveIdStatusEvent removeIdStatusEvent = new RemoveIdStatusEvent(); - removeIdStatusEvent.setData(Map.of(ID_HASH, idHash)); - removeIdStatusEvent.setTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - webSubHelper.publishEvent(removeIdStatusTopic, - webSubHelper.createEventModel(removeIdStatusTopic, removeIdStatusEvent)); - } private void handleDeactivateId(EventModel eventModel) throws IdAuthenticationBusinessException { updateIdentityMetadata(eventModel); diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/websub/impl/RemoveIdStatusEventPublisher.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/websub/impl/RemoveIdStatusEventPublisher.java new file mode 100644 index 00000000000..48e7c2ab1ed --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/websub/impl/RemoveIdStatusEventPublisher.java @@ -0,0 +1,92 @@ +package io.mosip.authentication.common.service.websub.impl; + +import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.REMOVE_ID_STATUS_TOPIC; + +import java.util.HashMap; +import java.util.Map; + +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.helper.WebSubHelper; +import io.mosip.authentication.common.service.impl.idevent.RemoveIdStatusEvent; +import io.mosip.authentication.core.constant.IdAuthCommonConstants; +import io.mosip.authentication.core.logger.IdaLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; + +/** + * The Class RemoveIdStatusEventPublisher. + * + * @author Ritik Jain + */ +@Component +public class RemoveIdStatusEventPublisher extends BaseWebSubEventsInitializer { + + /** The Constant logger. */ + private static final Logger logger = IdaLogger.getLogger(RemoveIdStatusEventPublisher.class); + + /** The remove id status topic. */ + @Value("${" + REMOVE_ID_STATUS_TOPIC + "}") + private String removeIdStatusTopic; + + /** The web sub event publish helper. */ + @Autowired + private WebSubHelper webSubHelper; + + private static final String ID_HASH = "id_hash"; + + /** + * Do subscribe. + */ + @Override + protected void doSubscribe() { + // Nothing to do here since we are just publishing event for this topic. + } + + /** + * Try register topic remove id status event. + */ + private void tryRegisterTopic() { + try { + logger.debug(IdAuthCommonConstants.SESSION_ID, "tryRegisterTopic", "", + "Trying to register topic: " + removeIdStatusTopic); + webSubHelper.registerTopic(removeIdStatusTopic); + logger.info(IdAuthCommonConstants.SESSION_ID, "tryRegisterTopic", "", + "Registered topic: " + removeIdStatusTopic); + } catch (Exception e) { + logger.info(IdAuthCommonConstants.SESSION_ID, "tryRegisterTopic", e.getClass().toString(), + "Error registering topic: " + removeIdStatusTopic + "\n" + e.getMessage()); + } + } + + @Override + protected void doRegister() { + logger.info(IdAuthCommonConstants.SESSION_ID, "doRegister", this.getClass().getSimpleName(), + "Registering topic.."); + tryRegisterTopic(); + } + + public void publishRemoveIdStatusEvent(String idHash) { + RemoveIdStatusEvent removeIdStatusEvent = createRemoveIdStatusEvent(idHash); + webSubHelper.publishEvent(removeIdStatusTopic, + webSubHelper.createEventModel(removeIdStatusTopic, removeIdStatusEvent)); + } + + /** + * Creates the remove id status event. + * + * @param idHash the idHash + * @return the remove id status event + */ + private RemoveIdStatusEvent createRemoveIdStatusEvent(String idHash) { + RemoveIdStatusEvent removeIdStatusEvent = new RemoveIdStatusEvent(); + Map dataMap = new HashMap(); + dataMap.put(ID_HASH, idHash); + removeIdStatusEvent.setData(dataMap); + removeIdStatusEvent.setTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + return removeIdStatusEvent; + } + +} diff --git a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/listener/InternalAuthWebSubInitializer.java b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/listener/InternalAuthWebSubInitializer.java index 2449ce885eb..3a1e8d7e848 100644 --- a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/listener/InternalAuthWebSubInitializer.java +++ b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/listener/InternalAuthWebSubInitializer.java @@ -16,6 +16,7 @@ import io.mosip.authentication.common.service.websub.impl.MasterDataUpdateEventInitializer; import io.mosip.authentication.common.service.websub.impl.PartnerCACertEventInitializer; import io.mosip.authentication.common.service.websub.impl.PartnerServiceEventsInitializer; +import io.mosip.authentication.common.service.websub.impl.RemoveIdStatusEventPublisher; /** * The Class InternalAuthWebSubInitializer. @@ -49,6 +50,10 @@ public class InternalAuthWebSubInitializer extends CacheUpdatingWebsubInitialize @Autowired private AuthTransactionStatusEventPublisher authTransactionStatusEventPublisher; + /** The remove id status event publisher. */ + @Autowired + private RemoveIdStatusEventPublisher removeIdStatusEventPublisher; + /** The partner service events subscriber. */ @Autowired private PartnerServiceEventsInitializer partnerServiceEventsInitializer; @@ -84,6 +89,7 @@ protected int doRegisterTopics() { webSubHelper.initRegistrar(credentialStoreStatusEventPublisher); webSubHelper.initRegistrar(authTypeStatusEventPublisher); webSubHelper.initRegistrar(authTransactionStatusEventPublisher); + webSubHelper.initRegistrar(removeIdStatusEventPublisher); if(Objects.nonNull(fraudEventPublisher)) webSubHelper.initRegistrar(fraudEventPublisher); return HttpStatus.SC_OK; From 3af325d5f523c1da41eff8aa3bbd4c4b55bd9992 Mon Sep 17 00:00:00 2001 From: RitikJain4108 <99730411+RitikJain4108@users.noreply.github.com> Date: Tue, 28 May 2024 21:22:47 +0530 Subject: [PATCH 4/9] [ES-558] Fixed application start issue (#1275) * update code to publish event Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * fix github build failure Signed-off-by: Ritik Jain (IN74108) * registered topic Signed-off-by: Ritik Jain (IN74108) * fixed application failed to start issue Signed-off-by: Ritik Jain (IN74108) --------- Signed-off-by: Ritik Jain (IN74108) Co-authored-by: Ritik Jain (IN74108) Co-authored-by: 61074108 <61074108@5CD12778H4> Signed-off-by: dhanendra06 --- .../internal/service/InternalAuthenticationApplication.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/InternalAuthenticationApplication.java b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/InternalAuthenticationApplication.java index 808ad5a3ffd..083ea7bc57b 100644 --- a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/InternalAuthenticationApplication.java +++ b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/InternalAuthenticationApplication.java @@ -65,6 +65,7 @@ import io.mosip.authentication.common.service.websub.impl.MasterDataUpdateEventInitializer; import io.mosip.authentication.common.service.websub.impl.PartnerCACertEventInitializer; import io.mosip.authentication.common.service.websub.impl.PartnerServiceEventsInitializer; +import io.mosip.authentication.common.service.websub.impl.RemoveIdStatusEventPublisher; import io.mosip.authentication.core.util.DemoMatcherUtil; import io.mosip.authentication.core.util.DemoNormalizer; import io.mosip.authentication.core.util.IdTypeUtil; @@ -129,7 +130,7 @@ CACertificateStore.class, PartnerCACertEventInitializer.class, PartnerCertManagerController.class, RetryConfig.class, RetryUtil.class, RetryListenerImpl.class, RetryAspect.class, CredentialStoreServiceImpl.class, CredentialStoreJobExecutionListener.class, HotlistServiceImpl.class, HotlistEventInitializer.class, - AuthTransactionHelper.class, CredentialStoreStatusEventPublisher.class, AuthTypeStatusEventPublisher.class, + AuthTransactionHelper.class, CredentialStoreStatusEventPublisher.class, AuthTypeStatusEventPublisher.class, RemoveIdStatusEventPublisher.class, AuthTransactionStatusEventPublisher.class, PartnerServiceEventsInitializer.class, CredentialRequestManager.class, DemoNormalizer.class, DemoMatcherUtil.class, IdAuthFraudAnalysisEventManager.class, IdAuthFraudAnalysisEventPublisher.class, AuthFiltersValidator.class, SessionKeyDecrytorHelper.class, InternalRestHelperConfig.class, IdaRequestResponsConsumerUtil.class, From 8d153080484128f53961dbd87c9e36a8eb73d302 Mon Sep 17 00:00:00 2001 From: RitikJain4108 <99730411+RitikJain4108@users.noreply.github.com> Date: Mon, 3 Jun 2024 14:07:54 +0530 Subject: [PATCH 5/9] [ES-558] Fixed 'EmptyResultDataAccessException' issue (#1280) * update code to publish event Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * added property Signed-off-by: Ritik Jain (IN74108) * fix github build failure Signed-off-by: Ritik Jain (IN74108) * registered topic Signed-off-by: Ritik Jain (IN74108) * fixed application failed to start issue Signed-off-by: Ritik Jain (IN74108) * fixed EmptyResultDataAccessException issue Signed-off-by: Ritik Jain (IN74108) --------- Signed-off-by: Ritik Jain (IN74108) Co-authored-by: Ritik Jain (IN74108) Co-authored-by: 61074108 <61074108@5CD12778H4> Signed-off-by: dhanendra06 --- .../service/impl/idevent/IdChangeEventHandlerServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java index c91749d4ccd..4c7a6c58dbb 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/idevent/IdChangeEventHandlerServiceImpl.java @@ -187,7 +187,7 @@ private void handleRemoveId(EventModel eventModel) throws IdAuthenticationBusine Event event = eventModel.getEvent(); Map additionalData = event.getData(); String idHash = (String) additionalData.get(ID_HASH); - if (idHash != null && !idHash.isEmpty()) { + if (idHash != null && !idHash.isEmpty() && identityCacheRepo.existsById(idHash)) { identityCacheRepo.deleteById(idHash); removeIdStatusEventPublisher.publishRemoveIdStatusEvent(idHash); } From d296b5c5aca2274bfdb0c3cd952620affcb54221 Mon Sep 17 00:00:00 2001 From: Muralitharan K Date: Fri, 7 Jun 2024 15:37:00 +0530 Subject: [PATCH 6/9] Numberformatexception handling (#1273) Signed-off-by: dhanendra06 --- .../java/io/mosip/authentication/core/util/IdTypeUtil.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/util/IdTypeUtil.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/util/IdTypeUtil.java index 7cb5386510a..3e3c1b92aaf 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/util/IdTypeUtil.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/util/IdTypeUtil.java @@ -41,7 +41,7 @@ public boolean validateUin(String uin) { return idValidator.validateUIN(uin); else return false; - } catch (InvalidIDException | IdAuthenticationBusinessException e) { + } catch (InvalidIDException | IdAuthenticationBusinessException | NumberFormatException e) { return false; } } @@ -52,7 +52,7 @@ public boolean validateVid(String vid) { return idValidator.validateVID(vid); else return false; - } catch (InvalidIDException | IdAuthenticationBusinessException e) { + } catch (InvalidIDException | IdAuthenticationBusinessException | NumberFormatException e) { return false; } } From 265b1c8fbc4a3d780cf3dc86fb01fe1a5ef8f7fa Mon Sep 17 00:00:00 2001 From: RitikJain4108 <99730411+RitikJain4108@users.noreply.github.com> Date: Mon, 10 Jun 2024 20:56:50 +0530 Subject: [PATCH 7/9] ES-558 updated push trigger (#1288) * fixed build issue Signed-off-by: Ritik Jain (IN74108) * updated push trigger Signed-off-by: Ritik Jain (IN74108) --------- Signed-off-by: Ritik Jain (IN74108) Co-authored-by: Ritik Jain (IN74108) Signed-off-by: dhanendra06 --- .github/workflows/push-trigger.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index da2a570e147..7f5fa751e44 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -20,6 +20,7 @@ on: - 1.* - develop - MOSIP* + - ES-842 jobs: build-maven-authentication: From f4c507f2b38d8c69e6bc70708b433eb603de90b9 Mon Sep 17 00:00:00 2001 From: ase-101 Date: Mon, 24 Jun 2024 15:15:39 +0530 Subject: [PATCH 8/9] resolved the conflict for MOSIP-32162 Signed-off-by: dhanendra06 --- .../esignet-integration-impl/pom.xml | 77 --- .../esignet/integration/dto/AuditRequest.java | 36 -- .../integration/dto/AuditResponse.java | 10 - .../dto/ClientIdSecretKeyRequest.java | 21 - .../dto/CredentialDefinitionDTO.java | 20 - .../esignet/integration/dto/Error.java | 20 - .../dto/GetAllCertificatesResponse.java | 18 - .../esignet/integration/dto/IdaError.java | 16 - .../integration/dto/IdaKycAuthRequest.java | 53 -- .../integration/dto/IdaKycAuthResponse.java | 16 - .../dto/IdaKycExchangeRequest.java | 24 - .../dto/IdaKycExchangeResponse.java | 14 - .../integration/dto/IdaOtpResponse.java | 14 - .../integration/dto/IdaResponseWrapper.java | 22 - .../integration/dto/IdaSendOtpRequest.java | 23 - .../integration/dto/IdaSendOtpResponse.java | 22 - .../integration/dto/IdaVcExchangeRequest.java | 40 -- .../dto/IdaVcExchangeResponse.java | 9 - .../integration/dto/KeyBindedToken.java | 12 - .../integration/dto/KeyBindingRequest.java | 22 - .../integration/dto/KeyBindingResponse.java | 16 - .../helper/AuthTransactionHelper.java | 77 --- .../helper/VCITransactionHelper.java | 30 -- .../integration/service/HelperService.java | 289 ----------- .../service/IdaAuditPluginImpl.java | 128 ----- .../service/IdaAuthenticatorImpl.java | 258 ---------- .../integration/service/IdaKeyBinderImpl.java | 176 ------- .../service/IdaVCIssuancePluginImpl.java | 214 -------- .../helper/AuthTransactionHelperTest.java | 46 -- .../helper/VCITransactionHelperTest.java | 49 -- .../service/HelperServiceTest.java | 265 ---------- .../service/IdaAuditPluginImplTest.java | 160 ------ .../service/IdaAuthenticatorImplTest.java | 466 ------------------ .../service/IdaKeyBinderImplTest.java | 188 ------- .../service/IdaVCIssuancePluginImplTest.java | 281 ----------- .../esignet/integration/service/TestUtil.java | 80 --- authentication/pom.xml | 8 +- 37 files changed, 4 insertions(+), 3216 deletions(-) delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/ClientIdSecretKeyRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/CredentialDefinitionDTO.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/Error.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/GetAllCertificatesResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaError.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaOtpResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaResponseWrapper.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindedToken.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingRequest.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingResponse.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelper.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelper.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelperTest.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelperTest.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/HelperServiceTest.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImplTest.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/TestUtil.java diff --git a/authentication/esignet-integration-impl/pom.xml b/authentication/esignet-integration-impl/pom.xml index 9d3075594d6..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/pom.xml +++ b/authentication/esignet-integration-impl/pom.xml @@ -1,77 +0,0 @@ - - 4.0.0 - - - io.mosip.authentication - authentication-parent - 1.2.1.0 - - 1.2.1.0 - esignet-integration-impl - esignet-integration-impl - e-Signet Integration Implementation Library - - - 11 - - - - - junit - junit - 4.13.1 - test - - - - org.projectlombok - lombok - 1.18.22 - compile - - - io.mosip.esignet - esignet-core - 1.3.0 - provided - - - io.mosip.esignet - esignet-integration-api - 1.3.0 - provided - - - - io.mosip.kernel - kernel-keymanager-service - ${kernel-keymanager-service.version} - provided - lib - - - org.springframework.cloud - spring-cloud-starter-sleuth - - - org.springframework.security - spring-security-test - - - - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - test - - - info.weboftrust - ld-signatures-java - 1.0.0 - - - \ No newline at end of file diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditRequest.java deleted file mode 100644 index b2335ebc21c..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditRequest.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.mosip.authentication.esignet.integration.dto; - -import java.time.LocalDateTime; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * The Class AuditRequestDto. - * - * @author Manoj SP - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class AuditRequest { - - private String eventId; - private String eventName; - private String eventType; - private LocalDateTime actionTimeStamp; - private String hostName; - private String hostIp; - private String applicationId; - private String applicationName; - private String sessionUserId; - private String sessionUserName; - private String id; - private String idType; - private String createdBy; - private String moduleName; - private String moduleId; - private String description; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditResponse.java deleted file mode 100644 index 595aa31a42f..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/AuditResponse.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class AuditResponse { - - private boolean status; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/ClientIdSecretKeyRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/ClientIdSecretKeyRequest.java deleted file mode 100644 index 3c6dda3b07a..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/ClientIdSecretKeyRequest.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class ClientIdSecretKeyRequest { - - private String clientId; - private String secretKey; - private String appId; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/CredentialDefinitionDTO.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/CredentialDefinitionDTO.java deleted file mode 100644 index af7a0a38848..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/CredentialDefinitionDTO.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; -import java.util.Map; - -import lombok.Data; - -@Data -public class CredentialDefinitionDTO { - - /** */ - private Map credentialSubject; - - /** */ - private List type; - - /** */ - private List context; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/Error.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/Error.java deleted file mode 100644 index 16d6c6f037b..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/Error.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Error { - - private String errorCode; - private String errorMessage; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/GetAllCertificatesResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/GetAllCertificatesResponse.java deleted file mode 100644 index d73daebb3a7..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/GetAllCertificatesResponse.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; - -import io.mosip.esignet.api.dto.KycSigningCertificateData; -import lombok.Data; - -@Data -public class GetAllCertificatesResponse { - - private List allCertificates; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaError.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaError.java deleted file mode 100644 index e967bb5e22e..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaError.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class IdaError { - - private String actionMessage; - private String errorCode; - private String errorMessage; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthRequest.java deleted file mode 100644 index 1465bb7129b..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthRequest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; -import java.util.Map; - -import lombok.Data; - -@Data -public class IdaKycAuthRequest { - - private String id; - private String version; - private String individualId; - private String individualIdType; - private String transactionID; - private String requestTime; - private String specVersion; - private String thumbprint; - private String domainUri; - private String env; - private boolean consentObtained; - private String request; - private String requestHMAC; - private String requestSessionKey; - private Map metadata; - private List allowedKycAttributes; - - @Data - public static class AuthRequest { - private String otp; - private String staticPin; - private String timestamp; - private List biometrics; - private List keyBindedTokens; - private String password; - } - - @Data - public static class Biometric { - private String data; - private String hash; - private String sessionKey; - private String specVersion; - private String thumbprint; - } - - -} \ No newline at end of file diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthResponse.java deleted file mode 100644 index f6724f6ab2c..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthResponse.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class IdaKycAuthResponse { - - private String kycToken; - private String authToken; - private boolean kycStatus; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeRequest.java deleted file mode 100644 index 78a6d123e29..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeRequest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class IdaKycExchangeRequest { - - private String id; - private String version; - private String requestTime; - private String transactionID; - private String kycToken; - private List consentObtained; - private List locales; - private String respType; - private String individualId; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeResponse.java deleted file mode 100644 index 01da00c1de1..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycExchangeResponse.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class IdaKycExchangeResponse { - - private String encryptedKyc; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaOtpResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaOtpResponse.java deleted file mode 100644 index 4d923a203de..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaOtpResponse.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class IdaOtpResponse { - private String maskedEmail; - private String maskedMobile; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaResponseWrapper.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaResponseWrapper.java deleted file mode 100644 index f9ee146f622..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaResponseWrapper.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class IdaResponseWrapper { - - private String id; - private String version; - private String transactionID; - private String responseTime; - private T response; - private List errors; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpRequest.java deleted file mode 100644 index 358cf0d6ae3..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpRequest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class IdaSendOtpRequest { - - private String id; - private String version; - private String individualId; - private String individualIdType; - private String transactionID; - private String requestTime; - private List otpChannel; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpResponse.java deleted file mode 100644 index c1ccb48ac65..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaSendOtpResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class IdaSendOtpResponse { - - private String id; - private String version; - private String transactionID; - private String responseTime; - private List errors; - private IdaOtpResponse response; -} - diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeRequest.java deleted file mode 100644 index 62360a9b436..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeRequest.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.mosip.authentication.esignet.integration.dto; - -import java.util.List; -import java.util.Map; - -import javax.validation.constraints.NotNull; -import lombok.Data; - -@Data -public class IdaVcExchangeRequest { - - @NotNull - private String vcAuthToken; - - /** The Variable to hold value of Credential Subject Id */ - @NotNull - private String credSubjectId; - - /** The Variable to hold value of VC Format type */ - @NotNull - private String vcFormat; - - /** The Variable to hold value of list of user selected locales */ - private List locales; - - private Map metadata; - - private String id; - - private String version; - - private String individualId; - - private String transactionID; - - private String requestTime; - - private CredentialDefinitionDTO credentialsDefinition; - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeResponse.java deleted file mode 100644 index 7d3b9d97699..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaVcExchangeResponse.java +++ /dev/null @@ -1,9 +0,0 @@ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class IdaVcExchangeResponse { - - private T verifiableCredentials; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindedToken.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindedToken.java deleted file mode 100644 index dbe00127abb..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindedToken.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.mosip.authentication.esignet.integration.dto; - - -import lombok.Data; - -@Data -public class KeyBindedToken { - - private String token; - private String type; - private String format; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingRequest.java deleted file mode 100644 index 214a0b6708c..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingRequest.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -import java.util.Map; - -@Data -public class KeyBindingRequest extends IdaKycAuthRequest { - - private IdentityKeyBinding identityKeyBinding; - - @Data - public static class IdentityKeyBinding { - private Map publicKeyJWK; - private String authFactorType; - } -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingResponse.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingResponse.java deleted file mode 100644 index e223bd3c019..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/KeyBindingResponse.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.dto; - -import lombok.Data; - -@Data -public class KeyBindingResponse { - - private String identityCertificate; - private String authToken; - private boolean bindingAuthStatus; -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelper.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelper.java deleted file mode 100644 index 9aff9e0be9d..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelper.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.mosip.authentication.esignet.integration.helper; - -import java.time.LocalDateTime; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.annotation.CacheEvict; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.authentication.esignet.integration.dto.ClientIdSecretKeyRequest; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseWrapper; -import lombok.extern.slf4j.Slf4j; - -@Component -@Slf4j -public class AuthTransactionHelper { - - private static final String AUTH_TOKEN_CACHE = "authtokens"; - - public static final String AUTH_TOKEN_CACHE_KEY = "auth_token"; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private RestTemplate restTemplate; - - @Value("${mosip.esignet.authenticator.ida.auth-token-url}") - private String authTokenUrl; - - @Value("${mosip.esignet.authenticator.ida.client-id}") - private String clientId; - - @Value("${mosip.esignet.authenticator.ida.secret-key}") - private String secretKey; - - @Value("${mosip.esignet.authenticator.ida.app-id}") - private String appId; - - @Cacheable(value = AUTH_TOKEN_CACHE, key = "#root.target.AUTH_TOKEN_CACHE_KEY") - public String getAuthToken() throws Exception { - log.info("Started to get auth-token with appId : {} && clientId : {}", - appId, clientId); - - RequestWrapper authRequest = new RequestWrapper<>(); - authRequest.setRequesttime(LocalDateTime.now()); - ClientIdSecretKeyRequest clientIdSecretKeyRequest = new ClientIdSecretKeyRequest(clientId, secretKey, appId); - authRequest.setRequest(clientIdSecretKeyRequest); - - String requestBody = objectMapper.writeValueAsString(authRequest); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(authTokenUrl).build().toUri()) - .contentType(MediaType.APPLICATION_JSON) - .body(requestBody); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference() {}); - - String authToken = responseEntity.getHeaders().getFirst("authorization"); - return authToken; - } - - @CacheEvict(value = AUTH_TOKEN_CACHE, allEntries = true) - public void purgeAuthTokenCache() { - log.info("Evicting entry from AUTH_TOKEN_CACHE"); - } - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelper.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelper.java deleted file mode 100644 index f8d607161f7..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelper.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.mosip.authentication.esignet.integration.helper; - -import java.util.Map; - -import io.mosip.esignet.core.dto.OIDCTransaction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.CacheManager; -import org.springframework.stereotype.Component; - -@Component -public class VCITransactionHelper { - - @Autowired - CacheManager cacheManager; - - @Value("${mosip.esignet.ida.vci-user-info-cache}") - private String userinfoCache; - - @SuppressWarnings("unchecked") - public OIDCTransaction getOAuthTransaction(String accessTokenHash) throws Exception { - if (cacheManager.getCache(userinfoCache) != null) { - return cacheManager.getCache(userinfoCache).get(accessTokenHash, OIDCTransaction.class); //NOSONAR getCache() will not be returning null here. - } - throw new Exception("cache_missing"); - } - - - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java index 5a95185da93..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java +++ b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java @@ -1,289 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.service; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.nimbusds.jwt.JWT; -import com.nimbusds.jwt.JWTParser; -import io.mosip.authentication.esignet.integration.dto.IdaKycAuthRequest; -import io.mosip.authentication.esignet.integration.dto.IdaSendOtpRequest; -import io.mosip.authentication.esignet.integration.dto.IdaSendOtpResponse; -import io.mosip.authentication.esignet.integration.dto.KeyBindedToken; -import io.mosip.esignet.api.dto.AuthChallenge; -import io.mosip.esignet.api.dto.SendOtpResult; -import io.mosip.esignet.api.exception.KycAuthException; -import io.mosip.esignet.api.exception.SendOtpException; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.crypto.jce.core.CryptoCore; -import io.mosip.kernel.keygenerator.bouncycastle.util.KeyGeneratorUtils; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.partnercertservice.util.PartnerCertificateManagerUtil; -import io.mosip.kernel.signature.dto.JWTSignatureRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureResponseDto; -import io.mosip.kernel.signature.service.SignatureService; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.NotImplementedException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -@Service -@Slf4j -public class HelperService { - - public static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - public static final String SIGNATURE_HEADER_NAME = "signature"; - public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - public static final String UTC_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - public static final String INVALID_PARTNER_CERTIFICATE = "invalid_partner_cert"; - public static final String OIDC_PARTNER_APP_ID = "OIDC_PARTNER"; - public static final String BINDING_TRANSACTION = "bindingtransaction"; - private static Base64.Encoder urlSafeEncoder; - private static Base64.Decoder urlSafeDecoder; - private static SecureRandom secureRandom; - - static { - urlSafeEncoder = Base64.getUrlEncoder().withoutPadding(); - urlSafeDecoder = Base64.getUrlDecoder(); - secureRandom = new SecureRandom(); - } - - @Value("${mosip.esignet.authenticator.ida-send-otp-id:mosip.identity.otp}") - private String sendOtpId; - - @Value("${mosip.esignet.authenticator.ida-send-otp-version:1.0}") - private String idaVersion; - - @Value("${mosip.esignet.authenticator.ida.cert-url}") - private String idaPartnerCertificateUrl; - - @Value("${mosip.esignet.authenticator.ida.send-otp-url}") - private String sendOtpUrl; - - @Value("${mosip.kernel.keygenerator.symmetric-algorithm-name}") - private String symmetricAlgorithm; - - @Value("${mosip.kernel.keygenerator.symmetric-key-length}") - private int symmetricKeyLength; - - @Autowired - private KeymanagerUtil keymanagerUtil; - - @Autowired - private SignatureService signatureService; - - @Autowired - private RestTemplate restTemplate; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private CryptoCore cryptoCore; - - private Certificate idaPartnerCertificate; - - @Cacheable(value = BINDING_TRANSACTION, key = "#idHash") - public String getTransactionId(String idHash) { - return HelperService.generateTransactionId(10); - } - - protected void setAuthRequest(List challengeList, IdaKycAuthRequest idaKycAuthRequest) throws Exception { - IdaKycAuthRequest.AuthRequest authRequest = new IdaKycAuthRequest.AuthRequest(); - authRequest.setTimestamp(HelperService.getUTCDateTime()); - challengeList.stream() - .filter( auth -> auth != null && auth.getAuthFactorType() != null) - .forEach( auth -> { buildAuthRequest(auth, authRequest); }); - - KeyGenerator keyGenerator = KeyGeneratorUtils.getKeyGenerator(symmetricAlgorithm, symmetricKeyLength); - final SecretKey symmetricKey = keyGenerator.generateKey(); - String request = objectMapper.writeValueAsString(authRequest); - String hexEncodedHash = HMACUtils2.digestAsPlainText(request.getBytes(StandardCharsets.UTF_8)); - idaKycAuthRequest.setRequest(HelperService.b64Encode(CryptoUtil.symmetricEncrypt(symmetricKey, - request.getBytes(StandardCharsets.UTF_8)))); - idaKycAuthRequest.setRequestHMAC(HelperService.b64Encode(CryptoUtil.symmetricEncrypt(symmetricKey, - hexEncodedHash.getBytes(StandardCharsets.UTF_8)))); - Certificate certificate = getIdaPartnerCertificate(); - idaKycAuthRequest.setThumbprint(HelperService.b64Encode(getCertificateThumbprint(certificate))); - log.info("IDA certificate thumbprint {}", idaKycAuthRequest.getThumbprint()); - idaKycAuthRequest.setRequestSessionKey(HelperService.b64Encode( - cryptoCore.asymmetricEncrypt(certificate.getPublicKey(), symmetricKey.getEncoded()))); - } - - - protected SendOtpResult sendOTP(String partnerId, String clientId, IdaSendOtpRequest idaSendOtpRequest) - throws SendOtpException, JsonProcessingException { - idaSendOtpRequest.setId(sendOtpId); - idaSendOtpRequest.setVersion(idaVersion); - idaSendOtpRequest.setRequestTime(getUTCDateTime()); - - //set signature header, body and invoke kyc exchange endpoint - String requestBody = objectMapper.writeValueAsString(idaSendOtpRequest); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(sendOtpUrl).pathSegment(partnerId, clientId).build().toUri()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .header(SIGNATURE_HEADER_NAME, getRequestSignature(requestBody)) - .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_NAME) - .body(requestBody); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, IdaSendOtpResponse.class); - if(responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - IdaSendOtpResponse idaSendOtpResponse = responseEntity.getBody(); - if(idaSendOtpRequest.getTransactionID().equals(idaSendOtpResponse.getTransactionID()) && idaSendOtpResponse.getResponse() != null){ - return new SendOtpResult(idaSendOtpResponse.getTransactionID(), - idaSendOtpResponse.getResponse().getMaskedEmail(), - idaSendOtpResponse.getResponse().getMaskedMobile()); - } - log.error("Errors in response received from IDA send-otp : {}", idaSendOtpResponse.getErrors()); - throw new SendOtpException(idaSendOtpResponse.getErrors().get(0).getErrorCode()); - } - log.error("Error response received from IDA (send-otp) with status : {}", responseEntity.getStatusCode()); - throw new SendOtpException(); - } - - protected String getRequestSignature(String request) { - JWTSignatureRequestDto jwtSignatureRequestDto = new JWTSignatureRequestDto(); - jwtSignatureRequestDto.setApplicationId(OIDC_PARTNER_APP_ID); - jwtSignatureRequestDto.setReferenceId(""); - jwtSignatureRequestDto.setIncludePayload(false); - jwtSignatureRequestDto.setIncludeCertificate(true); - jwtSignatureRequestDto.setDataToSign(HelperService.b64Encode(request)); - JWTSignatureResponseDto responseDto = signatureService.jwtSign(jwtSignatureRequestDto); - log.debug("Request signature ---> {}", responseDto.getJwtSignedData()); - return responseDto.getJwtSignedData(); - } - - protected Certificate getIdaPartnerCertificate() throws KycAuthException { - if(StringUtils.isEmpty(idaPartnerCertificate)) { - log.info("Fetching IDA partner certificate from : {}", idaPartnerCertificateUrl); - idaPartnerCertificate = keymanagerUtil.convertToCertificate(restTemplate.getForObject(idaPartnerCertificateUrl, - String.class)); - } - if(PartnerCertificateManagerUtil.isCertificateDatesValid((X509Certificate)idaPartnerCertificate)) - return idaPartnerCertificate; - - log.info("PARTNER CERTIFICATE IS NOT VALID, Downloading the certificate again"); - idaPartnerCertificate = keymanagerUtil.convertToCertificate(restTemplate.getForObject(idaPartnerCertificateUrl, - String.class)); - if(PartnerCertificateManagerUtil.isCertificateDatesValid((X509Certificate)idaPartnerCertificate)) - return idaPartnerCertificate; - - throw new KycAuthException(INVALID_PARTNER_CERTIFICATE); - } - - protected byte[] getCertificateThumbprint(Certificate certificate) { - try { - return DigestUtils.sha256(certificate.getEncoded()); - } catch (CertificateEncodingException e) { - log.error("Failed to get cert thumbprint", e); - } - return new byte[]{}; - } - - /** - * Output format : 2022-12-01T03:22:46.720Z - * @return Formatted datetime - */ - protected static String getUTCDateTime() { - return ZonedDateTime - .now(ZoneOffset.UTC) - .format(DateTimeFormatter.ofPattern(UTC_DATETIME_PATTERN)); - } - - protected static String b64Encode(byte[] bytes) { - return urlSafeEncoder.encodeToString(bytes); - } - - protected static String b64Encode(String value) { - return urlSafeEncoder.encodeToString(value.getBytes(StandardCharsets.UTF_8)); - } - - protected static byte[] b64Decode(String value) { - return urlSafeDecoder.decode(value); - } - - private void buildAuthRequest(AuthChallenge authChallenge, IdaKycAuthRequest.AuthRequest authRequest) { - log.info("Build kyc-auth request with authFactor : {}", authChallenge.getAuthFactorType()); - switch (authChallenge.getAuthFactorType().toUpperCase()) { - case "OTP" : authRequest.setOtp(authChallenge.getChallenge()); - break; - case "PIN" : authRequest.setStaticPin(authChallenge.getChallenge()); - break; - case "BIO" : - byte[] decodedBio = HelperService.b64Decode(authChallenge.getChallenge()); - try { - List biometrics = objectMapper.readValue(decodedBio, - new TypeReference>(){}); - authRequest.setBiometrics(biometrics); - } catch (Exception e) { - log.error("Failed to parse biometric capture response", e); - } - break; - case "WLA" : - List list = new ArrayList<>(); - KeyBindedToken keyBindedToken = new KeyBindedToken(); - keyBindedToken.setType(authChallenge.getAuthFactorType()); - keyBindedToken.setToken(authChallenge.getChallenge()); - keyBindedToken.setFormat(authChallenge.getFormat()); - list.add(keyBindedToken); - authRequest.setKeyBindedTokens(list); - break; - case "PWD" : authRequest.setPassword(authChallenge.getChallenge()); - break; - default: - throw new NotImplementedException("KYC auth not implemented"); - } - } - - protected static String generateTransactionId(int length) { - StringBuilder builder = new StringBuilder(); - for(int i=0; i request = new RequestWrapper<>(); - - AuditRequest auditRequest = new AuditRequest(); - auditRequest.setEventId(action.name()); - auditRequest.setEventName(action.name()); - auditRequest.setEventType(status.name()); - auditRequest.setActionTimeStamp(DateUtils.getUTCCurrentDateTime()); - auditRequest.setHostName("localhost"); - auditRequest.setHostIp("localhost"); - auditRequest.setApplicationId(ESIGNET); - auditRequest.setApplicationName(ESIGNET); - auditRequest.setSessionUserId(StringUtils.isEmpty(username)?"no-user":username); - auditRequest.setSessionUserName(StringUtils.isEmpty(username)?"no-user":username); - auditRequest.setIdType(audit.getIdType()); - auditRequest.setCreatedBy(this.getClass().getSimpleName()); - auditRequest.setModuleName(action.getModule()); - auditRequest.setModuleId(action.getModule()); - auditRequest.setDescription(getAuditDescription(audit)); - auditRequest.setId(audit.getTransactionId()); - - request.setRequest(auditRequest); - request.setId("ida"); - request.setRequesttime(DateUtils.getUTCCurrentDateTime()); - - String requestBody = objectMapper.writeValueAsString(request); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(auditManagerUrl).build().toUri()) - .contentType(MediaType.APPLICATION_JSON).header(HttpHeaders.COOKIE, "Authorization=" + authToken) - .body(requestBody); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference() { - }); - - if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - ResponseWrapper responseWrapper = responseEntity.getBody(); - if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { - log.error("Error response received from audit service with errors: {}", - responseWrapper.getErrors()); - } - } - - if(responseEntity.getStatusCode() == HttpStatus.FORBIDDEN || - responseEntity.getStatusCode() == HttpStatus.UNAUTHORIZED) { - log.error("Audit call failed with error: {}, issue with auth-token hence purging the auth-token-cache", - responseEntity.getStatusCode()); - authTransactionHelper.purgeAuthTokenCache(); - } - } catch (Exception e) { - log.error("LogAudit failed with error : {}", e); - } - } - - private String getAuditDescription(AuditDTO audit) throws JSONException { - JSONObject json = new JSONObject(); - json.put("clientId", audit.getClientId()); - json.put("relyingPartyId", audit.getRelyingPartyId()); - json.put("state", audit.getState()); - json.put("codeHash", audit.getCodeHash()); - json.put("accessTokenHash", audit.getAccessTokenHash()); - json.put("linkCodeHash", audit.getLinkedCodeHash()); - json.put("linkTransactionId", audit.getLinkedTransactionId()); - return json.toString(); - } - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java index 0b6597853d2..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java +++ b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java @@ -1,258 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.service; - -import java.util.Arrays; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.authentication.esignet.integration.dto.GetAllCertificatesResponse; -import io.mosip.authentication.esignet.integration.dto.IdaKycAuthRequest; -import io.mosip.authentication.esignet.integration.dto.IdaKycAuthResponse; -import io.mosip.authentication.esignet.integration.dto.IdaKycExchangeRequest; -import io.mosip.authentication.esignet.integration.dto.IdaKycExchangeResponse; -import io.mosip.authentication.esignet.integration.dto.IdaResponseWrapper; -import io.mosip.authentication.esignet.integration.dto.IdaSendOtpRequest; -import io.mosip.authentication.esignet.integration.helper.AuthTransactionHelper; -import io.mosip.esignet.api.dto.KycAuthDto; -import io.mosip.esignet.api.dto.KycAuthResult; -import io.mosip.esignet.api.dto.KycExchangeDto; -import io.mosip.esignet.api.dto.KycExchangeResult; -import io.mosip.esignet.api.dto.KycSigningCertificateData; -import io.mosip.esignet.api.dto.SendOtpDto; -import io.mosip.esignet.api.dto.SendOtpResult; -import io.mosip.esignet.api.exception.KycAuthException; -import io.mosip.esignet.api.exception.KycExchangeException; -import io.mosip.esignet.api.exception.KycSigningCertificateException; -import io.mosip.esignet.api.exception.SendOtpException; -import io.mosip.esignet.api.spi.Authenticator; -import io.mosip.esignet.api.util.ErrorConstants; -import io.mosip.kernel.core.http.ResponseWrapper; -import lombok.extern.slf4j.Slf4j; - - -@ConditionalOnProperty(value = "mosip.esignet.integration.authenticator", havingValue = "IdaAuthenticatorImpl") -@Component -@Slf4j -public class IdaAuthenticatorImpl implements Authenticator { - - public static final String SIGNATURE_HEADER_NAME = "signature"; - public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - public static final String KYC_EXCHANGE_TYPE = "oidc"; - - @Value("${mosip.esignet.authenticator.ida-auth-id:mosip.identity.kycauth}") - private String kycAuthId; - - @Value("${mosip.esignet.authenticator.ida-exchange-id:mosip.identity.kycexchange}") - private String kycExchangeId; - - @Value("${mosip.esignet.authenticator.ida-version:1.0}") - private String idaVersion; - - @Value("${mosip.esignet.authenticator.ida-domainUri}") - private String idaDomainUri; - - @Value("${mosip.esignet.authenticator.ida-env:Staging}") - private String idaEnv; - - @Value("${mosip.esignet.authenticator.ida.kyc-auth-url}") - private String kycAuthUrl; - - @Value("${mosip.esignet.authenticator.ida.kyc-exchange-url}") - private String kycExchangeUrl; - - @Value("${mosip.esignet.authenticator.ida.otp-channels}") - private List otpChannels; - - @Value("${mosip.esignet.authenticator.ida.get-certificates-url}") - private String getCertsUrl; - - @Value("${mosip.esignet.authenticator.ida.application-id:IDA}") - private String applicationId; - - @Value("${mosip.esignet.authenticator.ida.reference-id:SIGN}") - private String referenceId; - - @Value("${mosip.esignet.authenticator.ida.client-id}") - private String clientId; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private RestTemplate restTemplate; - - @Autowired - HelperService helperService; - - @Autowired - private AuthTransactionHelper authTransactionHelper; - - @Override - public KycAuthResult doKycAuth(String relyingPartyId, String clientId, KycAuthDto kycAuthDto) - throws KycAuthException { - log.info("Started to build kyc-auth request with transactionId : {} && clientId : {}", - kycAuthDto.getTransactionId(), clientId); - try { - IdaKycAuthRequest idaKycAuthRequest = new IdaKycAuthRequest(); - idaKycAuthRequest.setId(kycAuthId); - idaKycAuthRequest.setVersion(idaVersion); - idaKycAuthRequest.setRequestTime(HelperService.getUTCDateTime()); - idaKycAuthRequest.setDomainUri(idaDomainUri); - idaKycAuthRequest.setEnv(idaEnv); - idaKycAuthRequest.setConsentObtained(true); - idaKycAuthRequest.setIndividualId(kycAuthDto.getIndividualId()); - idaKycAuthRequest.setTransactionID(kycAuthDto.getTransactionId()); - helperService.setAuthRequest(kycAuthDto.getChallengeList(), idaKycAuthRequest); - - //set signature header, body and invoke kyc auth endpoint - String requestBody = objectMapper.writeValueAsString(idaKycAuthRequest); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(kycAuthUrl).pathSegment(relyingPartyId, clientId).build().toUri()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .header(SIGNATURE_HEADER_NAME, helperService.getRequestSignature(requestBody)) - .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_NAME) - .body(requestBody); - ResponseEntity> responseEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference>() {}); - - if(responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - IdaResponseWrapper responseWrapper = responseEntity.getBody(); - if(responseWrapper.getResponse() != null && responseWrapper.getResponse().isKycStatus() && responseWrapper.getResponse().getKycToken() != null) { - return new KycAuthResult(responseEntity.getBody().getResponse().getKycToken(), - responseEntity.getBody().getResponse().getAuthToken()); - } - log.error("Error response received from IDA KycStatus : {} && Errors: {}", - responseWrapper.getResponse().isKycStatus(), responseWrapper.getErrors()); - throw new KycAuthException(CollectionUtils.isEmpty(responseWrapper.getErrors()) ? - ErrorConstants.AUTH_FAILED : responseWrapper.getErrors().get(0).getErrorCode()); - } - - log.error("Error response received from IDA (Kyc-auth) with status : {}", responseEntity.getStatusCode()); - } catch (KycAuthException e) { throw e; } catch (Exception e) { - log.error("KYC-auth failed with transactionId : {} && clientId : {}", kycAuthDto.getTransactionId(), - clientId, e); - } - throw new KycAuthException(ErrorConstants.AUTH_FAILED); - } - - @Override - public KycExchangeResult doKycExchange(String relyingPartyId, String clientId, KycExchangeDto kycExchangeDto) - throws KycExchangeException { - log.info("Started to build kyc-exchange request with transactionId : {} && clientId : {}", - kycExchangeDto.getTransactionId(), clientId); - try { - IdaKycExchangeRequest idaKycExchangeRequest = new IdaKycExchangeRequest(); - idaKycExchangeRequest.setId(kycExchangeId); - idaKycExchangeRequest.setVersion(idaVersion); - idaKycExchangeRequest.setRequestTime(HelperService.getUTCDateTime()); - idaKycExchangeRequest.setTransactionID(kycExchangeDto.getTransactionId()); - idaKycExchangeRequest.setKycToken(kycExchangeDto.getKycToken()); - if (!CollectionUtils.isEmpty(kycExchangeDto.getAcceptedClaims())) { - idaKycExchangeRequest.setConsentObtained(kycExchangeDto.getAcceptedClaims()); - } else { - idaKycExchangeRequest.setConsentObtained(List.of("sub")); - } - idaKycExchangeRequest.setLocales(Arrays.asList(kycExchangeDto.getClaimsLocales())); - idaKycExchangeRequest.setRespType(kycExchangeDto.getUserInfoResponseType()); //may be either JWT or JWE - idaKycExchangeRequest.setIndividualId(kycExchangeDto.getIndividualId()); - - //set signature header, body and invoke kyc exchange endpoint - String requestBody = objectMapper.writeValueAsString(idaKycExchangeRequest); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(kycExchangeUrl).pathSegment(relyingPartyId, - clientId).build().toUri()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .header(SIGNATURE_HEADER_NAME, helperService.getRequestSignature(requestBody)) - .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_NAME) - .body(requestBody); - ResponseEntity> responseEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference>() {}); - - if(responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - IdaResponseWrapper responseWrapper = responseEntity.getBody(); - if(responseWrapper.getResponse() != null && responseWrapper.getResponse().getEncryptedKyc() != null) { - return new KycExchangeResult(responseWrapper.getResponse().getEncryptedKyc()); - } - log.error("Errors in response received from IDA Kyc Exchange: {}", responseWrapper.getErrors()); - throw new KycExchangeException(CollectionUtils.isEmpty(responseWrapper.getErrors()) ? - ErrorConstants.DATA_EXCHANGE_FAILED : responseWrapper.getErrors().get(0).getErrorCode()); - } - - log.error("Error response received from IDA (Kyc-exchange) with status : {}", responseEntity.getStatusCode()); - } catch (KycExchangeException e) { throw e; } catch (Exception e) { - log.error("IDA Kyc-exchange failed with clientId : {}", clientId, e); - } - throw new KycExchangeException(); - } - - @Override - public SendOtpResult sendOtp(String relyingPartyId, String clientId, SendOtpDto sendOtpDto) throws SendOtpException { - log.info("Started to build send-otp request with transactionId : {} && clientId : {}", - sendOtpDto.getTransactionId(), clientId); - try { - IdaSendOtpRequest idaSendOtpRequest = new IdaSendOtpRequest(); - idaSendOtpRequest.setOtpChannel(sendOtpDto.getOtpChannels()); - idaSendOtpRequest.setIndividualId(sendOtpDto.getIndividualId()); - idaSendOtpRequest.setTransactionID(sendOtpDto.getTransactionId()); - return helperService.sendOTP(relyingPartyId, clientId, idaSendOtpRequest); - } catch (SendOtpException e) { - throw e; - } catch (Exception e) { - log.error("send-otp failed with clientId : {}", clientId, e); - } - throw new SendOtpException(); - } - - @Override - public boolean isSupportedOtpChannel(String channel) { - return channel != null && otpChannels.contains(channel.toLowerCase()); - } - - @Override - public List getAllKycSigningCertificates() throws KycSigningCertificateException { - try { - String authToken = authTransactionHelper.getAuthToken(); - - RequestEntity requestEntity = RequestEntity - .get(UriComponentsBuilder.fromUriString(getCertsUrl).queryParam("applicationId", applicationId).queryParam("referenceId", referenceId).build().toUri()) - .header(HttpHeaders.COOKIE, "Authorization=" + authToken) - .build(); - - ResponseEntity> responseEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference>() {}); - - if(responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - ResponseWrapper responseWrapper = responseEntity.getBody(); - if(responseWrapper.getResponse() != null && responseWrapper.getResponse().getAllCertificates() != null) { - return responseWrapper.getResponse().getAllCertificates(); - } - log.error("Error response received from getAllSigningCertificates with errors: {}", - responseWrapper.getErrors()); - throw new KycSigningCertificateException(CollectionUtils.isEmpty(responseWrapper.getErrors()) ? - ErrorConstants.KYC_SIGNING_CERTIFICATE_FAILED : responseWrapper.getErrors().get(0).getErrorCode()); - } - log.error("Error response received from getAllSigningCertificates with status : {}", responseEntity.getStatusCode()); - } catch (KycSigningCertificateException e) { throw e; } catch (Exception e) { - log.error("getAllKycSigningCertificates failed with clientId : {}", clientId, e); - } - throw new KycSigningCertificateException(); - } -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java index 2848be4f3cb..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java +++ b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java @@ -1,176 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.service; - - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.authentication.esignet.integration.dto.IdaResponseWrapper; -import io.mosip.authentication.esignet.integration.dto.IdaSendOtpRequest; -import io.mosip.authentication.esignet.integration.dto.KeyBindingRequest; -import io.mosip.authentication.esignet.integration.dto.KeyBindingResponse; -import io.mosip.esignet.api.dto.AuthChallenge; -import io.mosip.esignet.api.dto.KeyBindingResult; -import io.mosip.esignet.api.dto.SendOtpResult; -import io.mosip.esignet.api.exception.KeyBindingException; -import io.mosip.esignet.api.exception.SendOtpException; -import io.mosip.esignet.api.spi.KeyBinder; -import io.mosip.esignet.api.util.ErrorConstants; -import lombok.extern.slf4j.Slf4j; - -@ConditionalOnProperty(value = "mosip.esignet.integration.key-binder", havingValue = "IdaKeyBinderImpl") -@Component -@Slf4j -public class IdaKeyBinderImpl implements KeyBinder { - - private static final Map> supportedFormats = new HashMap<>(); - static { - supportedFormats.put("OTP", Arrays.asList("alpha-numeric")); - supportedFormats.put("PIN", Arrays.asList("number")); - supportedFormats.put("BIO", Arrays.asList("encoded-json")); - supportedFormats.put("WLA", Arrays.asList("jwt")); - } - - private static final String PARTNER_ID_HEADER = "partner-id"; - private static final String PARTNER_API_KEY_HEADER = "partner-api-key"; - public static final String SIGNATURE_HEADER_NAME = "signature"; - public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - public static final String REQUIRED_HEADERS_MISSING = "required_header_missing"; - - @Value("${mosip.esignet.binder.ida.key-binding-url}") - private String keyBinderUrl; - - @Value("${mosip.esignet.binder.ida-binding-id:mosip.identity.keybinding}") - private String keyBindingId; - - @Value("${mosip.esignet.authenticator.ida-version:1.0}") - private String idaVersion; - - @Value("${mosip.esignet.authenticator.ida-domainUri}") - private String idaDomainUri; - - @Value("${mosip.esignet.authenticator.ida-env:Staging}") - private String idaEnv; - - @Autowired - private HelperService helperService; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private RestTemplate restTemplate; - - @Override - public SendOtpResult sendBindingOtp(String individualId, List otpChannels, Map requestHeaders) - throws SendOtpException { - log.info("Started to send-binding-otp request"); - try { - if(StringUtils.isEmpty(requestHeaders.get(PARTNER_ID_HEADER)) || StringUtils.isEmpty(requestHeaders.get(PARTNER_API_KEY_HEADER))) - throw new SendOtpException(REQUIRED_HEADERS_MISSING); - - IdaSendOtpRequest idaSendOtpRequest = new IdaSendOtpRequest(); - idaSendOtpRequest.setOtpChannel(otpChannels); - idaSendOtpRequest.setIndividualId(individualId); - idaSendOtpRequest.setTransactionID(helperService.getTransactionId(HelperService.generateHash(individualId.trim()))); - return helperService.sendOTP(requestHeaders.get(PARTNER_ID_HEADER), - requestHeaders.get(PARTNER_API_KEY_HEADER), idaSendOtpRequest); - } catch (SendOtpException e) { - throw e; - } catch (Exception e) { - log.error("send-binding-otp failed with requestHeaders : {}", requestHeaders, e); - } - throw new SendOtpException(); - } - - @Override - public KeyBindingResult doKeyBinding(String individualId, List challengeList, Map publicKeyJWK, - String bindAuthFactorType, Map requestHeaders) throws KeyBindingException { - log.info("Started to key-binding request for auth-factor-type {}", bindAuthFactorType); - if(StringUtils.isEmpty(requestHeaders.get(PARTNER_ID_HEADER)) || StringUtils.isEmpty(requestHeaders.get(PARTNER_API_KEY_HEADER))) - throw new KeyBindingException(REQUIRED_HEADERS_MISSING); - - try { - KeyBindingRequest keyBindingRequest = new KeyBindingRequest(); - keyBindingRequest.setId(keyBindingId); - keyBindingRequest.setVersion(idaVersion); - keyBindingRequest.setRequestTime(HelperService.getUTCDateTime()); - keyBindingRequest.setDomainUri(idaDomainUri); - keyBindingRequest.setEnv(idaEnv); - keyBindingRequest.setConsentObtained(true); - keyBindingRequest.setIndividualId(individualId); - keyBindingRequest.setTransactionID(helperService.getTransactionId(HelperService.generateHash(individualId.trim()))); - helperService.setAuthRequest(challengeList, keyBindingRequest); - - KeyBindingRequest.IdentityKeyBinding identityKeyBinding = new KeyBindingRequest.IdentityKeyBinding(); - identityKeyBinding.setPublicKeyJWK(publicKeyJWK); - identityKeyBinding.setAuthFactorType(bindAuthFactorType); - keyBindingRequest.setIdentityKeyBinding(identityKeyBinding); - - //set signature header, body and invoke kyc auth endpoint - String requestBody = objectMapper.writeValueAsString(keyBindingRequest); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(keyBinderUrl).pathSegment(requestHeaders.getOrDefault(PARTNER_ID_HEADER, PARTNER_ID_HEADER), - requestHeaders.getOrDefault(PARTNER_API_KEY_HEADER, PARTNER_API_KEY_HEADER)).build().toUri()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .header(SIGNATURE_HEADER_NAME, helperService.getRequestSignature(requestBody)) - .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_NAME) - .body(requestBody); - ResponseEntity> responseEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference>() {}); - - if(responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - IdaResponseWrapper responseWrapper = responseEntity.getBody(); - if(responseWrapper.getResponse() == null) { - log.error("Error response received from IDA (Key-binding) Errors: {}", responseWrapper.getErrors()); - throw new KeyBindingException(CollectionUtils.isEmpty(responseWrapper.getErrors()) ? - ErrorConstants.KEY_BINDING_FAILED : responseWrapper.getErrors().get(0).getErrorCode()); - } - - if(!responseWrapper.getResponse().isBindingAuthStatus()) { - log.error("Binding-Auth-status : {}", responseWrapper.getResponse().isBindingAuthStatus()); - throw new KeyBindingException(ErrorConstants.BINDING_AUTH_FAILED); - } - - KeyBindingResult keyBindingResult = new KeyBindingResult(); - keyBindingResult.setCertificate(responseWrapper.getResponse().getIdentityCertificate()); - keyBindingResult.setPartnerSpecificUserToken(responseWrapper.getResponse().getAuthToken()); - return keyBindingResult; - } - - log.error("Error response received from IDA (Key-binding) with status : {}", responseEntity.getStatusCode()); - } catch (KeyBindingException e) { - throw e; - } catch (Exception e) { - log.error("Key-binding failed with headers: {}", requestHeaders, e); - } - throw new KeyBindingException(ErrorConstants.KEY_BINDING_FAILED); - } - - @Override - public List getSupportedChallengeFormats(String authFactorType) { - return supportedFormats.getOrDefault(authFactorType, Arrays.asList()); - } - -} diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java deleted file mode 100644 index afd43cdf1db..00000000000 --- a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImpl.java +++ /dev/null @@ -1,214 +0,0 @@ -package io.mosip.authentication.esignet.integration.service; - -import java.security.Key; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.util.*; -import java.util.stream.Collectors; - -import javax.crypto.Cipher; - -import io.mosip.authentication.esignet.integration.dto.IdaVcExchangeResponse; -import io.mosip.esignet.api.exception.VCIExchangeException; -import io.mosip.esignet.api.util.ErrorConstants; -import io.mosip.esignet.core.dto.OIDCTransaction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import foundation.identity.jsonld.JsonLDObject; -import io.mosip.authentication.esignet.integration.dto.IdaResponseWrapper; -import io.mosip.authentication.esignet.integration.dto.IdaVcExchangeRequest; -import io.mosip.authentication.esignet.integration.dto.CredentialDefinitionDTO; -import io.mosip.authentication.esignet.integration.helper.VCITransactionHelper; -import io.mosip.esignet.api.dto.VCRequestDto; -import io.mosip.esignet.api.dto.VCResult; -import io.mosip.esignet.api.spi.VCIssuancePlugin; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import lombok.extern.slf4j.Slf4j; - -@Component -@Slf4j -@ConditionalOnProperty(value = "mosip.esignet.integration.vci-plugin", havingValue = "IdaVCIssuancePluginImpl") -public class IdaVCIssuancePluginImpl implements VCIssuancePlugin { - private static final String CLIENT_ID = "client_id"; - private static final String ACCESS_TOKEN_HASH = "accessTokenHash"; - public static final String SIGNATURE_HEADER_NAME = "signature"; - public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - public static final String OIDC_SERVICE_APP_ID = "OIDC_SERVICE"; - public static final String AES_CIPHER_FAILED = "aes_cipher_failed"; - public static final String NO_UNIQUE_ALIAS = "no_unique_alias"; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private RestTemplate restTemplate; - - @Autowired - HelperService helperService; - - @Autowired - private KeyStore keyStore; - - @Autowired - private KeymanagerDBHelper dbHelper; - - @Autowired - VCITransactionHelper vciTransactionHelper; - - @Value("${mosip.esignet.ida.vci-exchange-url}") - private String vciExchangeUrl; - - @Value("${mosip.esignet.ida.vci-exchange-id}") - private String vciExchangeId; - - @Value("${mosip.esignet.ida.vci-exchange-version}") - private String vciExchangeVersion; - - @Value("${mosip.esignet.cache.secure.individual-id}") - private boolean secureIndividualId; - - @Value("${mosip.esignet.cache.store.individual-id}") - private boolean storeIndividualId; - - @Value("${mosip.esignet.cache.security.algorithm-name}") - private String aesECBTransformation; - - @Value("${mosip.esignet.cache.security.secretkey.reference-id}") - private String cacheSecretKeyRefId; - - private Base64.Decoder urlSafeDecoder = Base64.getUrlDecoder(); - - - @Override - public VCResult getVerifiableCredentialWithLinkedDataProof(VCRequestDto vcRequestDto, String holderId, - Map identityDetails) throws VCIExchangeException { - log.info("Started to created the VCIssuance"); - try { - OIDCTransaction transaction = vciTransactionHelper - .getOAuthTransaction(identityDetails.get(ACCESS_TOKEN_HASH).toString()); - String individualId = getIndividualId(transaction.getIndividualId()); - IdaVcExchangeRequest idaVciExchangeRequest = new IdaVcExchangeRequest(); - CredentialDefinitionDTO vciCred = new CredentialDefinitionDTO(); - idaVciExchangeRequest.setId(vciExchangeId);// Configuration - idaVciExchangeRequest.setVersion(vciExchangeVersion);// Configuration - idaVciExchangeRequest.setRequestTime(HelperService.getUTCDateTime()); - idaVciExchangeRequest.setTransactionID(transaction.getAuthTransactionId());// Cache input - idaVciExchangeRequest.setVcAuthToken(transaction.getKycToken()); // Cache input - idaVciExchangeRequest.setIndividualId(individualId); - idaVciExchangeRequest.setCredSubjectId(holderId); - idaVciExchangeRequest.setVcFormat(vcRequestDto.getFormat()); - idaVciExchangeRequest.setLocales(convertLangCodesToISO3LanguageCodes(transaction.getClaimsLocales())); - vciCred.setCredentialSubject(vcRequestDto.getCredentialSubject()); - vciCred.setType(vcRequestDto.getType()); - vciCred.setContext(vcRequestDto.getContext()); - idaVciExchangeRequest.setCredentialsDefinition(vciCred); - - String requestBody = objectMapper.writeValueAsString(idaVciExchangeRequest); - RequestEntity requestEntity = RequestEntity - .post(UriComponentsBuilder.fromUriString(vciExchangeUrl) - .pathSegment(transaction.getRelyingPartyId(), - identityDetails.get(CLIENT_ID).toString()) - .build().toUri()) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .header(SIGNATURE_HEADER_NAME, helperService.getRequestSignature(requestBody)) - .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_NAME).body(requestBody); - - ResponseEntity>> responseEntity = restTemplate.exchange( - requestEntity, new ParameterizedTypeReference>>() {}); - if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) { - IdaResponseWrapper> responseWrapper = responseEntity.getBody(); - if (responseWrapper != null && responseWrapper.getResponse() != null) - { - VCResult vCResult = new VCResult(); - vCResult.setCredential(responseWrapper.getResponse().getVerifiableCredentials()); - vCResult.setFormat(vcRequestDto.getFormat()); - return vCResult; - } - log.error("Errors in response received from IDA VCI Exchange: {}", responseWrapper.getErrors()); //NOSONAR responseWrapper is already evaluated to be not null - throw new VCIExchangeException(CollectionUtils.isEmpty(responseWrapper.getErrors()) ? - ErrorConstants.DATA_EXCHANGE_FAILED : responseWrapper.getErrors().get(0).getErrorCode()); - } - log.error("Error response received from IDA (VCI-exchange) with status : {}", responseEntity.getStatusCode()); - } catch (VCIExchangeException e) { throw e; } catch (Exception e) { - log.error("IDA Vci-exchange failed ", e); - } - throw new VCIExchangeException(); - } - - @Override - public VCResult getVerifiableCredential(VCRequestDto vcRequestDto, String holderId, - Map identityDetails) throws VCIExchangeException { - throw new VCIExchangeException(ErrorConstants.NOT_IMPLEMENTED); - } - - protected String getIndividualId(String encryptedIndividualId) throws Exception { - if (!storeIndividualId) - return null; - return secureIndividualId ? decryptIndividualId(encryptedIndividualId) : encryptedIndividualId; - } - - private String decryptIndividualId(String encryptedIndividualId) throws Exception { - try { - Cipher cipher = Cipher.getInstance(aesECBTransformation); - byte[] decodedBytes = b64Decode(encryptedIndividualId); - cipher.init(Cipher.DECRYPT_MODE, getSecretKeyFromHSM()); - return new String(cipher.doFinal(decodedBytes, 0, decodedBytes.length)); - } catch (Exception e) { - log.error("Error Cipher Operations of provided secret data.", e); - throw new Exception(AES_CIPHER_FAILED); - } - } - - private Key getSecretKeyFromHSM() throws Exception { - String keyAlias = getKeyAlias(OIDC_SERVICE_APP_ID, cacheSecretKeyRefId); - if (Objects.nonNull(keyAlias)) { - return keyStore.getSymmetricKey(keyAlias); - } - throw new Exception(NO_UNIQUE_ALIAS); - } - - private String getKeyAlias(String keyAppId, String keyRefId) throws Exception { - Map> keyAliasMap = dbHelper.getKeyAliases(keyAppId, keyRefId, - LocalDateTime.now(ZoneOffset.UTC)); - List currentKeyAliases = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - if (!currentKeyAliases.isEmpty() && currentKeyAliases.size() == 1) { - return currentKeyAliases.get(0).getAlias(); - } - log.error("CurrentKeyAlias is not unique. KeyAlias count: {}", currentKeyAliases.size()); - throw new Exception(NO_UNIQUE_ALIAS); - } - - private byte[] b64Decode(String value) { - return urlSafeDecoder.decode(value); - }; - - //Converts an array of two-letter language codes to their corresponding ISO 639-2/T language codes. - private List convertLangCodesToISO3LanguageCodes(String[] langCodes) { - if(langCodes == null || langCodes.length == 0 || (langCodes.length == 1 && langCodes[0].isEmpty())) - return List.of(); - return Arrays.stream(langCodes) - .map(langCode -> { - try { - return new Locale(langCode).getISO3Language(); - } catch (MissingResourceException ex) {} - return null; - }) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelperTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelperTest.java deleted file mode 100644 index a959bd35fdb..00000000000 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/AuthTransactionHelperTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.mosip.authentication.esignet.integration.helper; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.mosip.esignet.core.dto.ResponseWrapper; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class AuthTransactionHelperTest { - - @Mock - ObjectMapper objectMapper; - - @Mock - RestTemplate restTemplate; - - @InjectMocks - AuthTransactionHelper authTransactionHelper; - - @Test - public void GetAuthTokenWithValidDetails_thenPass() throws Exception { - ReflectionTestUtils.setField(authTransactionHelper, "authTokenUrl", "test"); - ReflectionTestUtils.setField(authTransactionHelper, "clientId", "test"); - ReflectionTestUtils.setField(authTransactionHelper,"secretKey","test"); - ReflectionTestUtils.setField(authTransactionHelper,"appId","test"); String expectedAuthToken = "testAuthToken"; - - ResponseEntity responseEntity = ResponseEntity.ok() - .header("authorization", expectedAuthToken) - .build(); - when(restTemplate.exchange(Mockito.any(RequestEntity.class), Mockito.any(ParameterizedTypeReference.class))) - .thenReturn(responseEntity); - String authToken = authTransactionHelper.getAuthToken(); - Assert.assertEquals(expectedAuthToken, authToken); - } -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelperTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelperTest.java deleted file mode 100644 index 28e309785bb..00000000000 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/helper/VCITransactionHelperTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.mosip.authentication.esignet.integration.helper; - -import io.mosip.esignet.core.dto.OIDCTransaction; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.cache.support.NoOpCache; -import org.springframework.test.util.ReflectionTestUtils; - -@RunWith(MockitoJUnitRunner.class) -public class VCITransactionHelperTest { - - @Mock - CacheManager cacheManager; - - @Mock - Cache cache=new NoOpCache("test"); - - @InjectMocks - VCITransactionHelper vciTransactionHelper; - - @Test - public void getOAuthTransactionWithValidDetails_thenPass() throws Exception { - ReflectionTestUtils.setField(vciTransactionHelper, "userinfoCache", "test"); - OIDCTransaction oidcTransaction = new OIDCTransaction(); - oidcTransaction.setTransactionId("test"); - Mockito.when(cacheManager.getCache(Mockito.anyString())).thenReturn(cache); - Mockito.when(cache.get("test",OIDCTransaction.class)).thenReturn(oidcTransaction); - vciTransactionHelper.getOAuthTransaction("test"); - - } - - @Test - public void getOAuthTransactionWithInValidDetails_thenFail() { - try{ - vciTransactionHelper.getOAuthTransaction("test"); - }catch (Exception e){ - assert(e.getMessage().equals("cache_missing")); - } - - - } - -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/HelperServiceTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/HelperServiceTest.java deleted file mode 100644 index 7e66a33a45e..00000000000 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/HelperServiceTest.java +++ /dev/null @@ -1,265 +0,0 @@ -package io.mosip.authentication.esignet.integration.service; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.mosip.authentication.esignet.integration.dto.*; -import io.mosip.authentication.esignet.integration.dto.Error; -import io.mosip.esignet.api.dto.AuthChallenge; -import io.mosip.esignet.api.dto.SendOtpResult; -import io.mosip.esignet.api.exception.SendOtpException; -import io.mosip.kernel.crypto.jce.core.CryptoCore; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.signature.dto.JWTSignatureResponseDto; -import io.mosip.kernel.signature.service.SignatureService; -import org.apache.commons.lang3.NotImplementedException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; - -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -@RunWith(MockitoJUnitRunner.class) -public class HelperServiceTest { - - @InjectMocks - private HelperService helperService; - - @Mock - private KeymanagerUtil keymanagerUtil; - - @Mock - private SignatureService signatureService; - - @Mock - private RestTemplate restTemplate; - - @Mock - private CryptoCore cryptoCore; - - String partnerId = "test"; - String partnerAPIKey = "test-api-key"; - - ObjectMapper objectMapper = new ObjectMapper(); - - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - ReflectionTestUtils.setField(helperService, "sendOtpUrl", "https://test/test"); - ReflectionTestUtils.setField(helperService, "idaPartnerCertificateUrl", "https://test/test"); - ReflectionTestUtils.setField(helperService, "symmetricAlgorithm", "AES"); - ReflectionTestUtils.setField(helperService, "symmetricKeyLength", 256); - ReflectionTestUtils.setField(helperService, "objectMapper", objectMapper); - } - - @Test - public void sendOtp_requestSignatureFailed_thenFail() { - JWTSignatureResponseDto jwtSignatureResponseDto = new JWTSignatureResponseDto(); - jwtSignatureResponseDto.setJwtSignedData("test-jwt"); - Mockito.when(signatureService.jwtSign(Mockito.any())).thenThrow(RuntimeException.class); - IdaSendOtpRequest sendOtpRequest = new IdaSendOtpRequest(); - Assert.assertThrows(Exception.class, () -> helperService.sendOTP(partnerId, partnerAPIKey, sendOtpRequest)); - } - - @Test - public void sendOtp_withNullResponse_thenFail() { - JWTSignatureResponseDto jwtSignatureResponseDto = new JWTSignatureResponseDto(); - jwtSignatureResponseDto.setJwtSignedData("test-jwt"); - Mockito.when(signatureService.jwtSign(Mockito.any())).thenReturn(jwtSignatureResponseDto); - - ResponseEntity responseEntity = new ResponseEntity(HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.any())).thenReturn(responseEntity); - IdaSendOtpRequest sendOtpRequest = new IdaSendOtpRequest(); - Assert.assertThrows(SendOtpException.class, () -> helperService.sendOTP(partnerId, partnerAPIKey, sendOtpRequest)); - } - - @Test - public void sendOtp_withValidResponse_thenPass() throws Exception { - JWTSignatureResponseDto jwtSignatureResponseDto = new JWTSignatureResponseDto(); - jwtSignatureResponseDto.setJwtSignedData("test-jwt"); - Mockito.when(signatureService.jwtSign(Mockito.any())).thenReturn(jwtSignatureResponseDto); - - IdaSendOtpResponse idaSendOtpResponse = new IdaSendOtpResponse(); - idaSendOtpResponse.setTransactionID("123456788"); - IdaOtpResponse idaOtpResponse = new IdaOtpResponse(); - idaOtpResponse.setMaskedEmail("masked-mail"); - new IdaOtpResponse().setMaskedMobile("masked-mobile"); - idaSendOtpResponse.setResponse(idaOtpResponse); - ResponseEntity responseEntity = new ResponseEntity( - idaSendOtpResponse, HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.any())).thenReturn(responseEntity); - IdaSendOtpRequest sendOtpRequest = new IdaSendOtpRequest(); - sendOtpRequest.setTransactionID("123456788"); - SendOtpResult sendOtpResult = helperService.sendOTP(partnerId, partnerAPIKey, sendOtpRequest); - Assert.assertEquals(idaSendOtpResponse.getTransactionID(), sendOtpResult.getTransactionId()); - Assert.assertEquals(idaOtpResponse.getMaskedEmail(), sendOtpResult.getMaskedEmail()); - Assert.assertEquals(idaOtpResponse.getMaskedMobile(), sendOtpResult.getMaskedMobile()); - } - - @Test - public void sendOtp_withErrorResponse_thenFail() { - JWTSignatureResponseDto jwtSignatureResponseDto = new JWTSignatureResponseDto(); - jwtSignatureResponseDto.setJwtSignedData("test-jwt"); - Mockito.when(signatureService.jwtSign(Mockito.any())).thenReturn(jwtSignatureResponseDto); - - IdaSendOtpResponse idaSendOtpResponse = new IdaSendOtpResponse(); - idaSendOtpResponse.setTransactionID("123456788"); - idaSendOtpResponse.setErrors(Arrays.asList(new Error("otp-error", "otp-error"))); - ResponseEntity responseEntity = new ResponseEntity( - idaSendOtpResponse, HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.any())).thenReturn(responseEntity); - - IdaSendOtpRequest sendOtpRequest = new IdaSendOtpRequest(); - sendOtpRequest.setTransactionID("123456788"); - try { - helperService.sendOTP(partnerId, partnerAPIKey, sendOtpRequest); - } catch (SendOtpException e) { - Assert.assertEquals("otp-error", e.getErrorCode()); - } catch (JsonProcessingException e) { - Assert.fail(); - } - } - - @Test - public void setAuthRequest_withInvalidChallengeType_thenFail() { - List challengeList = new ArrayList<>(); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setChallenge("test"); - authChallenge.setAuthFactorType("Test"); - challengeList.add(authChallenge); - Assert.assertThrows(NotImplementedException.class, - () -> helperService.setAuthRequest(challengeList, new IdaKycAuthRequest())); - } - - @Test - public void setAuthRequest_withOTPChallengeType_thenPass() throws Exception { - List challengeList = new ArrayList<>(); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setChallenge("111333"); - authChallenge.setAuthFactorType("otp"); - authChallenge.setFormat("numeric"); - challengeList.add(authChallenge); - - Mockito.when(restTemplate.getForObject("https://test/test", String.class)).thenReturn("test-certificate"); - Mockito.when(keymanagerUtil.convertToCertificate(Mockito.any(String.class))).thenReturn(TestUtil.getCertificate()); - Mockito.when(cryptoCore.asymmetricEncrypt(Mockito.any(), Mockito.any())).thenReturn("test".getBytes()); - - IdaKycAuthRequest idaKycAuthRequest = new IdaKycAuthRequest(); - helperService.setAuthRequest(challengeList, idaKycAuthRequest); - Assert.assertNotNull(idaKycAuthRequest.getRequest()); - Assert.assertNotNull(idaKycAuthRequest.getRequestSessionKey()); - Assert.assertNotNull(idaKycAuthRequest.getRequestHMAC()); - Assert.assertNotNull(idaKycAuthRequest.getThumbprint()); - } - - @Test - public void setAuthRequest_withPWDChallengeType_thenPass() throws Exception { - List challengeList = new ArrayList<>(); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setChallenge("password"); - authChallenge.setAuthFactorType("pwd"); - authChallenge.setFormat("numeric"); - challengeList.add(authChallenge); - - Mockito.when(restTemplate.getForObject("https://test/test", String.class)).thenReturn("test-certificate"); - Mockito.when(keymanagerUtil.convertToCertificate(Mockito.any(String.class))).thenReturn(TestUtil.getCertificate()); - Mockito.when(cryptoCore.asymmetricEncrypt(Mockito.any(), Mockito.any())).thenReturn("test".getBytes()); - - IdaKycAuthRequest idaKycAuthRequest = new IdaKycAuthRequest(); - helperService.setAuthRequest(challengeList, idaKycAuthRequest); - Assert.assertNotNull(idaKycAuthRequest.getRequest()); - Assert.assertNotNull(idaKycAuthRequest.getRequestSessionKey()); - Assert.assertNotNull(idaKycAuthRequest.getRequestHMAC()); - Assert.assertNotNull(idaKycAuthRequest.getThumbprint()); - } - - @Test - public void setAuthRequest_withPINChallengeType_thenPass() throws Exception { - List challengeList = new ArrayList<>(); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setChallenge("111333"); - authChallenge.setAuthFactorType("pin"); - authChallenge.setFormat("numeric"); - challengeList.add(authChallenge); - - Mockito.when(restTemplate.getForObject("https://test/test", String.class)).thenReturn("test-certificate"); - Mockito.when(keymanagerUtil.convertToCertificate(Mockito.any(String.class))).thenReturn(TestUtil.getCertificate()); - Mockito.when(cryptoCore.asymmetricEncrypt(Mockito.any(), Mockito.any())).thenReturn("test".getBytes()); - - IdaKycAuthRequest idaKycAuthRequest = new IdaKycAuthRequest(); - helperService.setAuthRequest(challengeList, idaKycAuthRequest); - Assert.assertNotNull(idaKycAuthRequest.getRequest()); - Assert.assertNotNull(idaKycAuthRequest.getRequestSessionKey()); - Assert.assertNotNull(idaKycAuthRequest.getRequestHMAC()); - Assert.assertNotNull(idaKycAuthRequest.getThumbprint()); - } - - @Test - public void setAuthRequest_withBIOChallengeType_thenPass() throws Exception { - IdaKycAuthRequest.Biometric biometric = new IdaKycAuthRequest.Biometric(); - biometric.setData("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cmFuc2FjdGlvbklkIjoiMTIzNDU2Nzg5MCIsIm5hbWUiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0=.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); - List list = new ArrayList<>(); - list.add(biometric); - String value = objectMapper.writeValueAsString(list); - - List challengeList = new ArrayList<>(); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setChallenge(HelperService.b64Encode(value)); - authChallenge.setAuthFactorType("bio"); - authChallenge.setFormat("numeric"); - challengeList.add(authChallenge); - - Mockito.when(restTemplate.getForObject("https://test/test", String.class)).thenReturn("test-certificate"); - Mockito.when(keymanagerUtil.convertToCertificate(Mockito.any(String.class))).thenReturn(TestUtil.getCertificate()); - Mockito.when(cryptoCore.asymmetricEncrypt(Mockito.any(), Mockito.any())).thenReturn("test".getBytes()); - - IdaKycAuthRequest idaKycAuthRequest = new IdaKycAuthRequest(); - helperService.setAuthRequest(challengeList, idaKycAuthRequest); - Assert.assertNotNull(idaKycAuthRequest.getRequest()); - Assert.assertNotNull(idaKycAuthRequest.getRequestSessionKey()); - Assert.assertNotNull(idaKycAuthRequest.getRequestHMAC()); - Assert.assertNotNull(idaKycAuthRequest.getThumbprint()); - } - - @Test - public void getIdaPartnerCertificate_withUnsetPartnerCertificate_thenPass() throws Exception { - Mockito.when(restTemplate.getForObject("https://test/test", String.class)).thenReturn("test-certificate"); - Certificate certificate = TestUtil.getCertificate(); - Mockito.when(keymanagerUtil.convertToCertificate(Mockito.any(String.class))).thenReturn(certificate); - Assert.assertEquals(certificate, helperService.getIdaPartnerCertificate()); - } - - @Test - public void getIdaPartnerCertificate_withExpiredPartnerCertificate_thenPass() throws Exception { - Mockito.when(restTemplate.getForObject("https://test/test", String.class)).thenReturn("test-certificate", "test-certificate"); - Certificate certificate = TestUtil.getCertificate(); - Mockito.when(keymanagerUtil.convertToCertificate(Mockito.any(String.class))).thenReturn(TestUtil.getExpiredCertificate(), certificate); - Assert.assertEquals(certificate, helperService.getIdaPartnerCertificate()); - } - - @Test - public void getRequestSignature_validation() { - JWTSignatureResponseDto jwtSignatureResponseDto = new JWTSignatureResponseDto(); - jwtSignatureResponseDto.setJwtSignedData("test-jwt"); - Mockito.when(signatureService.jwtSign(Mockito.any())).thenReturn(jwtSignatureResponseDto); - Assert.assertEquals("test-jwt", helperService.getRequestSignature("test-request-value")); - } -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java index ceda8fd7c41..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java +++ b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java @@ -1,160 +0,0 @@ -package io.mosip.authentication.esignet.integration.service; - -import io.mosip.esignet.api.dto.AuditDTO; -import io.mosip.esignet.api.util.Action; -import io.mosip.esignet.api.util.ActionStatus; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.junit.MockitoJUnitRunner; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.mosip.authentication.esignet.integration.dto.AuditResponse; -import io.mosip.authentication.esignet.integration.helper.AuthTransactionHelper; -import io.mosip.kernel.core.http.ResponseWrapper; -import org.mockito.*; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; -import static org.mockito.ArgumentMatchers.*; - -@RunWith(MockitoJUnitRunner.class) -public class IdaAuditPluginImplTest { - @InjectMocks - private IdaAuditPluginImpl idaAuditPlugin; - @Mock - private AuthTransactionHelper authTransactionHelper; - @Mock - private ObjectMapper objectMapper; - @Mock - private RestTemplate restTemplate; - @Test - public void logAudit_WithValidDetails_ThenPass() { - Action action = Action.AUTHENTICATE; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - try { - idaAuditPlugin.logAudit(action, status, auditDTO, null); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } - @Test - public void logAudit_WithThrowable_ThenPass() { - Action action = Action.GENERATE_TOKEN; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - Throwable throwable = new RuntimeException("Test Exception"); - try { - idaAuditPlugin.logAudit(action, status, auditDTO, throwable); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } - @Test - public void logAudit_WithUsername_WithValidDetails_ThenPass() { - String username = "username"; - Action action = Action.OIDC_CLIENT_UPDATE; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - try { - idaAuditPlugin.logAudit(username, action, status, auditDTO, null); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } - - @Test - public void logAudit_WithUsername_WithThrowable() throws Exception { - String username = "username"; - Action action = Action.GENERATE_TOKEN; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - Throwable throwable = new RuntimeException("Test Exception"); - try { - idaAuditPlugin.logAudit(username,action, status, auditDTO, throwable); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } - @Test - public void logAudit_WithValidStatus_ThenPass() throws Exception { - ReflectionTestUtils.setField(idaAuditPlugin, "auditManagerUrl", "auditManagerUrl"); - String username = "username"; - Action action = Action.SAVE_CONSENT; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - ResponseWrapper mockresponseWrapper = new ResponseWrapper<>(); - ResponseEntity responseEntity = ResponseEntity.ok(mockresponseWrapper); - ParameterizedTypeReference responseType = - new ParameterizedTypeReference() { - }; - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("authToken"); - Mockito.when(objectMapper.writeValueAsString(any())).thenReturn("requestBody"); - Mockito.when(restTemplate.exchange( - Mockito.any(RequestEntity.class), - Mockito.eq(responseType) - )).thenReturn(responseEntity); - try { - idaAuditPlugin.logAudit(username,action, status, auditDTO, null); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } - @Test - public void logAudit_WithUnauthorizedStatus_ThenPass() throws Exception { - ReflectionTestUtils.setField(idaAuditPlugin, "auditManagerUrl", "auditManagerUrl"); - String username = "username"; - Action action = Action.SAVE_CONSENT; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - ResponseWrapper mockresponseWrapper = new ResponseWrapper<>(); - ResponseEntity responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(mockresponseWrapper); - ParameterizedTypeReference responseType = - new ParameterizedTypeReference() { - }; - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("authToken"); - Mockito.when(objectMapper.writeValueAsString(any())).thenReturn("requestBody"); - Mockito.when(restTemplate.exchange( - Mockito.any(RequestEntity.class), - Mockito.eq(responseType) - )).thenReturn(responseEntity); - try { - idaAuditPlugin.logAudit(username,action, status, auditDTO, null); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } - @Test - public void logAudit_WithForbiddenStatus_ThenPass() throws Exception { - ReflectionTestUtils.setField(idaAuditPlugin, "auditManagerUrl", "auditManagerUrl"); - String username = "username"; - Action action = Action.SAVE_CONSENT; - ActionStatus status = ActionStatus.SUCCESS; - AuditDTO auditDTO = new AuditDTO(); - ResponseWrapper mockresponseWrapper = new ResponseWrapper<>(); - ResponseEntity responseEntity = ResponseEntity.status(HttpStatus.FORBIDDEN).body(mockresponseWrapper); - ParameterizedTypeReference responseType = - new ParameterizedTypeReference() { - }; - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("authToken"); - Mockito.when(objectMapper.writeValueAsString(any())).thenReturn("requestBody"); - Mockito.when(restTemplate.exchange( - Mockito.any(RequestEntity.class), - Mockito.eq(responseType) - )).thenReturn(responseEntity); - try { - idaAuditPlugin.logAudit(username,action, status, auditDTO, null); - Assert.assertTrue(true); - } catch (Exception e) { - Assert.fail(); - } - } -} \ No newline at end of file diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImplTest.java deleted file mode 100644 index cad47ce0a5a..00000000000 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImplTest.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.service; - -import static org.mockito.ArgumentMatchers.any; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.authentication.esignet.integration.dto.GetAllCertificatesResponse; -import io.mosip.authentication.esignet.integration.dto.IdaKycAuthRequest.Biometric; -import io.mosip.authentication.esignet.integration.dto.IdaKycAuthResponse; -import io.mosip.authentication.esignet.integration.dto.IdaKycExchangeResponse; -import io.mosip.authentication.esignet.integration.dto.IdaResponseWrapper; -import io.mosip.authentication.esignet.integration.helper.AuthTransactionHelper; -import io.mosip.esignet.api.dto.AuthChallenge; -import io.mosip.esignet.api.dto.KycAuthDto; -import io.mosip.esignet.api.dto.KycAuthResult; -import io.mosip.esignet.api.dto.KycExchangeDto; -import io.mosip.esignet.api.dto.KycExchangeResult; -import io.mosip.esignet.api.dto.KycSigningCertificateData; -import io.mosip.esignet.api.dto.SendOtpDto; -import io.mosip.esignet.api.dto.SendOtpResult; -import io.mosip.esignet.api.exception.KycAuthException; -import io.mosip.esignet.api.exception.KycExchangeException; -import io.mosip.esignet.api.exception.KycSigningCertificateException; -import io.mosip.esignet.api.exception.SendOtpException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; - -@SpringBootTest -@RunWith(MockitoJUnitRunner.class) -public class IdaAuthenticatorImplTest { - - @InjectMocks - IdaAuthenticatorImpl idaAuthenticatorImpl; - - @Mock - ObjectMapper mapper; - - @Mock - RestTemplate restTemplate; - - @Mock - HelperService helperService; - - @Mock - AuthTransactionHelper authTransactionHelper; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - ReflectionTestUtils.setField(helperService, "sendOtpUrl", "https:/"); - ReflectionTestUtils.setField(helperService, "idaPartnerCertificateUrl", "https://test"); - ReflectionTestUtils.setField(helperService, "symmetricAlgorithm", "AES"); - ReflectionTestUtils.setField(helperService, "symmetricKeyLength", 256); - - ReflectionTestUtils.setField(idaAuthenticatorImpl, "kycExchangeUrl", "https://dev.mosip.net"); - ReflectionTestUtils.setField(idaAuthenticatorImpl, "idaVersion", "VersionIDA"); - ReflectionTestUtils.setField(idaAuthenticatorImpl, "kycAuthUrl", "https://testkycAuthUrl"); - ReflectionTestUtils.setField(idaAuthenticatorImpl, "getCertsUrl", "https://testGetCertsUrl"); - ReflectionTestUtils.setField(idaAuthenticatorImpl, "otpChannels", Arrays.asList("otp", "pin", "bio")); - } - - @Test - public void doKycAuth_withInvalidDetails_throwsException() throws Exception { - KycAuthDto kycAuthDto = new KycAuthDto(); - kycAuthDto.setIndividualId("IND1234"); - kycAuthDto.setTransactionId("TRAN1234"); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setAuthFactorType("PIN"); - authChallenge.setChallenge("111111"); - List authChallengeList = new ArrayList<>(); - authChallengeList.add(authChallenge); - kycAuthDto.setChallengeList(authChallengeList); - - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())).thenReturn(null); - - Assert.assertThrows(KycAuthException.class, - () -> idaAuthenticatorImpl.doKycAuth("relyingId", "clientId", kycAuthDto)); - } - - @Test - public void doKycAuth_withValidDetails_thenPass() throws Exception { - KycAuthDto kycAuthDto = new KycAuthDto(); - kycAuthDto.setIndividualId("IND1234"); - kycAuthDto.setTransactionId("TRAN1234"); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setAuthFactorType("OTP"); - authChallenge.setChallenge("111111"); - List authChallengeList = new ArrayList<>(); - authChallengeList.add(authChallenge); - kycAuthDto.setChallengeList(authChallengeList); - - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - - IdaKycAuthResponse idaKycAuthResponse = new IdaKycAuthResponse(); - idaKycAuthResponse.setAuthToken("authToken1234"); - idaKycAuthResponse.setKycToken("kycToken1234"); - idaKycAuthResponse.setKycStatus(true); - - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - idaResponseWrapper.setResponse(idaKycAuthResponse); - idaResponseWrapper.setTransactionID("TRAN123"); - idaResponseWrapper.setVersion("VER1"); - - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - KycAuthResult kycAuthResult = idaAuthenticatorImpl.doKycAuth("relyingId", "clientId", kycAuthDto); - - Assert.assertEquals(kycAuthResult.getKycToken(), kycAuthResult.getKycToken()); - } - - @Test - public void doKycAuth_withAuthChallengeNull_thenFail() throws Exception { - KycAuthDto kycAuthDto = new KycAuthDto(); - kycAuthDto.setIndividualId("IND1234"); - kycAuthDto.setTransactionId("TRAN1234"); - kycAuthDto.setChallengeList(null); - - Assert.assertThrows(KycAuthException.class, - () -> idaAuthenticatorImpl.doKycAuth("relyingId", "clientId", kycAuthDto)); - } - - @Test - public void doKycAuth_withInvalidAuthChallenge_thenFail() throws Exception { - KycAuthDto kycAuthDto = new KycAuthDto(); - kycAuthDto.setIndividualId("IND1234"); - kycAuthDto.setTransactionId("TRAN1234"); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setAuthFactorType("Test"); - authChallenge.setChallenge("111111"); - List authChallengeList = new ArrayList<>(); - authChallengeList.add(authChallenge); - kycAuthDto.setChallengeList(authChallengeList); - - Assert.assertThrows(KycAuthException.class, - () -> idaAuthenticatorImpl.doKycAuth("relyingId", "clientId", kycAuthDto)); - } - - @Test - public void doKycAuth_withBIOAuthChallenge_thenPass() throws Exception { - KycAuthDto kycAuthDto = new KycAuthDto(); - kycAuthDto.setIndividualId("IND1234"); - kycAuthDto.setTransactionId("TRAN1234"); - AuthChallenge authChallenge = new AuthChallenge(); - authChallenge.setAuthFactorType("BIO"); - authChallenge.setChallenge("111111"); - List authChallengeList = new ArrayList<>(); - authChallengeList.add(authChallenge); - kycAuthDto.setChallengeList(authChallengeList); - - Biometric b = new Biometric(); - b.setData( - "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); - b.setHash("Hash"); - b.setSessionKey("SessionKey"); - b.setSpecVersion("SepecV"); - b.setThumbprint("Thumbprint"); - List bioList = new ArrayList<>(); - bioList.add(b); - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - IdaKycAuthResponse idaKycAuthResponse = new IdaKycAuthResponse(); - idaKycAuthResponse.setAuthToken("authToken1234"); - idaKycAuthResponse.setKycToken("kycToken1234"); - idaKycAuthResponse.setKycStatus(true); - - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - idaResponseWrapper.setResponse(idaKycAuthResponse); - idaResponseWrapper.setTransactionID("TRAN123"); - idaResponseWrapper.setVersion("VER1"); - - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - KycAuthResult kycAuthResult = idaAuthenticatorImpl.doKycAuth("relyingId", "clientId", kycAuthDto); - - Assert.assertEquals(kycAuthResult.getKycToken(), kycAuthResult.getKycToken()); - } - - @Test - public void doKycExchange_withValidDetails_thenPass() throws Exception { - KycExchangeDto kycExchangeDto = new KycExchangeDto(); - kycExchangeDto.setIndividualId("IND1234"); - kycExchangeDto.setKycToken("KYCT123"); - kycExchangeDto.setTransactionId("TRAN123"); - List acceptedClaims = new ArrayList<>(); - acceptedClaims.add("claims"); - kycExchangeDto.setAcceptedClaims(acceptedClaims); - String[] claimsLacales = new String[] { "claims", "locales" }; - kycExchangeDto.setClaimsLocales(claimsLacales); - - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - - IdaKycExchangeResponse idaKycExchangeResponse = new IdaKycExchangeResponse(); - idaKycExchangeResponse.setEncryptedKyc("ENCRKYC123"); - - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - idaResponseWrapper.setResponse(idaKycExchangeResponse); - idaResponseWrapper.setTransactionID("TRAN123"); - idaResponseWrapper.setVersion("VER1"); - - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - KycExchangeResult kycExchangeResult = idaAuthenticatorImpl.doKycExchange("relyingPartyId", "clientId", - kycExchangeDto); - - Assert.assertEquals(idaKycExchangeResponse.getEncryptedKyc(), kycExchangeResult.getEncryptedKyc()); - } - - - @Test - public void doKycExchange_withValidDetailsEmptyAcceptedClaims_thenPass() throws Exception { - KycExchangeDto kycExchangeDto = new KycExchangeDto(); - kycExchangeDto.setIndividualId("IND1234"); - kycExchangeDto.setKycToken("KYCT123"); - kycExchangeDto.setTransactionId("TRAN123"); - List acceptedClaims = List.of(); - kycExchangeDto.setAcceptedClaims(acceptedClaims); - String[] claimsLacales = new String[] { "claims", "locales" }; - kycExchangeDto.setClaimsLocales(claimsLacales); - - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - - IdaKycExchangeResponse idaKycExchangeResponse = new IdaKycExchangeResponse(); - idaKycExchangeResponse.setEncryptedKyc("ENCRKYC123"); - - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - idaResponseWrapper.setResponse(idaKycExchangeResponse); - idaResponseWrapper.setTransactionID("TRAN123"); - idaResponseWrapper.setVersion("VER1"); - - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - KycExchangeResult kycExchangeResult = idaAuthenticatorImpl.doKycExchange("relyingPartyId", "clientId", - kycExchangeDto); - - Assert.assertEquals(idaKycExchangeResponse.getEncryptedKyc(), kycExchangeResult.getEncryptedKyc()); - } - - @Test - public void doKycExchange_withInvalidDetails_thenFail() throws Exception { - KycExchangeDto kycExchangeDto = new KycExchangeDto(); - kycExchangeDto.setIndividualId(null); - kycExchangeDto.setKycToken("KYCT123"); - kycExchangeDto.setTransactionId("TRAN123"); - List acceptedClaims = new ArrayList<>(); - acceptedClaims.add("claims"); - kycExchangeDto.setAcceptedClaims(acceptedClaims); - String[] claimsLacales = new String[] { "claims", "locales" }; - kycExchangeDto.setClaimsLocales(claimsLacales); - - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - - IdaKycExchangeResponse idaKycExchangeResponse = new IdaKycExchangeResponse(); - idaKycExchangeResponse.setEncryptedKyc("ENCRKYC123"); - - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - idaResponseWrapper.setResponse(null); - idaResponseWrapper.setTransactionID("TRAN123"); - idaResponseWrapper.setVersion("VER1"); - - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - Assert.assertThrows(KycExchangeException.class, - () -> idaAuthenticatorImpl.doKycExchange("test-relyingPartyId", "test-clientId", kycExchangeDto)); - } - - @Test - public void doKycExchange_withInvalidIndividualId_throwsException() throws KycExchangeException, Exception { - KycExchangeDto kycExchangeDto = new KycExchangeDto(); - kycExchangeDto.setIndividualId("IND1234"); - kycExchangeDto.setKycToken("KYCT123"); - kycExchangeDto.setTransactionId("TRAN123"); - List acceptedClaims = new ArrayList<>(); - acceptedClaims.add("claims"); - kycExchangeDto.setAcceptedClaims(acceptedClaims); - String[] claimsLacales = new String[] { "claims", "locales" }; - kycExchangeDto.setClaimsLocales(claimsLacales); - - Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("value"); - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(null); - - Assert.assertThrows(KycExchangeException.class, - () -> idaAuthenticatorImpl.doKycExchange("relyingId", "clientId", kycExchangeDto)); - } - - @Test - public void sendOtp_withValidDetails_thenPass() throws Exception { - SendOtpDto sendOtpDto = new SendOtpDto(); - sendOtpDto.setIndividualId("1234"); - sendOtpDto.setTransactionId("4567"); - List otpChannelsList = new ArrayList<>(); - otpChannelsList.add("channel"); - sendOtpDto.setOtpChannels(otpChannelsList); - - Mockito.when(helperService.sendOTP(any(),any(),any())).thenReturn(new SendOtpResult(sendOtpDto.getTransactionId(), "", "")); - - SendOtpResult sendOtpResult = idaAuthenticatorImpl.sendOtp("rly123", "cli123", sendOtpDto); - - Assert.assertEquals(sendOtpDto.getTransactionId(), sendOtpResult.getTransactionId()); - } - - @Test - public void sendOtp_withErrorResponse_throwsException() throws Exception { - SendOtpDto sendOtpDto = new SendOtpDto(); - sendOtpDto.setIndividualId(null); - sendOtpDto.setTransactionId("4567"); - List otpChannelsList = new ArrayList<>(); - otpChannelsList.add("channel"); - sendOtpDto.setOtpChannels(otpChannelsList); - - Mockito.when(helperService.sendOTP(any(),any(),any())).thenThrow(new SendOtpException("error-100")); - - try { - idaAuthenticatorImpl.sendOtp("rly123", "cli123", sendOtpDto); - Assert.fail(); - } catch (SendOtpException e) { - Assert.assertEquals("error-100", e.getErrorCode()); - } - } - - @Test - public void isSupportedOtpChannel_withInvalidChannel_thenFail() { - Assert.assertFalse(idaAuthenticatorImpl.isSupportedOtpChannel("test")); - } - - @Test - public void isSupportedOtpChannel_withValidChannel_thenPass() { - Assert.assertTrue(idaAuthenticatorImpl.isSupportedOtpChannel("OTP")); - } - - @Test - public void getAllKycSigningCertificates_withValidDetails_thenPass() throws Exception { - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("test-token"); - - GetAllCertificatesResponse getAllCertificatesResponse = new GetAllCertificatesResponse(); - getAllCertificatesResponse.setAllCertificates(new ArrayList()); - - ResponseWrapper certsResponseWrapper = new ResponseWrapper(); - certsResponseWrapper.setId("test-id"); - certsResponseWrapper.setResponse(getAllCertificatesResponse); - - ResponseEntity> certsResponseEntity = new ResponseEntity>( - certsResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(certsResponseEntity); - - List signingCertificates = new ArrayList<>(); - - signingCertificates = idaAuthenticatorImpl.getAllKycSigningCertificates(); - - Assert.assertSame(signingCertificates, getAllCertificatesResponse.getAllCertificates()); - } - - @Test - public void getAllKycSigningCertificates_withInvalidResponse_throwsException() throws Exception { - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("test-token"); - - ResponseWrapper certsResponseWrapper = new ResponseWrapper(); - certsResponseWrapper.setId("test-id"); - List errors = new ArrayList<>(); - ServiceError error = new ServiceError("ERR-001", "Certificates not found"); - errors.add(error); - certsResponseWrapper.setErrors(errors); - - ResponseEntity> certsResponseEntity = new ResponseEntity>( - certsResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(certsResponseEntity); - - Assert.assertThrows(KycSigningCertificateException.class, - () -> idaAuthenticatorImpl.getAllKycSigningCertificates()); - } - - @Test - public void getAllKycSigningCertificates_withErrorResponse_throwsException() throws Exception { - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("test-token"); - - ResponseWrapper certsResponseWrapper = new ResponseWrapper(); - certsResponseWrapper.setId("test-id"); - List errors = new ArrayList<>(); - ServiceError error = new ServiceError("ERR-001", "Certificates not found"); - errors.add(error); - certsResponseWrapper.setErrors(errors); - - ResponseEntity> certsResponseEntity = new ResponseEntity>( - certsResponseWrapper, HttpStatus.FORBIDDEN); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(certsResponseEntity); - - Assert.assertThrows(KycSigningCertificateException.class, - () -> idaAuthenticatorImpl.getAllKycSigningCertificates()); - } - - @SuppressWarnings("rawtypes") - @Test - public void getAllKycSigningCertificates_withInvalidToken_thenFail() throws Exception { - Mockito.when(authTransactionHelper.getAuthToken()).thenReturn("test-token"); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>any())).thenThrow(RuntimeException.class); - - Assert.assertThrows(KycSigningCertificateException.class, - () -> idaAuthenticatorImpl.getAllKycSigningCertificates()); - } - -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java index 47d3d69d9dd..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java +++ b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java @@ -1,188 +0,0 @@ -package io.mosip.authentication.esignet.integration.service; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.mosip.authentication.esignet.integration.dto.*; -import io.mosip.esignet.api.dto.KeyBindingResult; -import io.mosip.esignet.api.dto.SendOtpDto; -import io.mosip.esignet.api.dto.SendOtpResult; -import io.mosip.esignet.api.exception.KeyBindingException; -import io.mosip.esignet.api.exception.SendOtpException; -import io.mosip.esignet.api.util.ErrorConstants; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.parameters.P; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; - -import java.util.*; - -import static org.mockito.ArgumentMatchers.any; - -@RunWith(MockitoJUnitRunner.class) -public class IdaKeyBinderImplTest { - - @InjectMocks - private IdaKeyBinderImpl idaKeyBinderImpl; - - @Mock - private HelperService helperService; - - @Mock - private RestTemplate restTemplate; - - private ObjectMapper objectMapper = new ObjectMapper(); - private static final String PARTNER_ID_HEADER = "partner-id"; - private static final String PARTNER_API_KEY_HEADER = "partner-api-key"; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - ReflectionTestUtils.setField(idaKeyBinderImpl, "keyBinderUrl", "https://localhost/identity-key-binding/mispLK/"); - ReflectionTestUtils.setField(idaKeyBinderImpl, "objectMapper", objectMapper); - } - - @Test - public void sendBindingOtp_withValidDetails_thenPass() throws Exception { - SendOtpDto sendOtpDto = new SendOtpDto(); - sendOtpDto.setIndividualId("1234"); - sendOtpDto.setTransactionId("4567"); - List otpChannelsList = new ArrayList<>(); - otpChannelsList.add("channel"); - sendOtpDto.setOtpChannels(otpChannelsList); - Map headers = new HashMap<>(); - headers.put(PARTNER_ID_HEADER, PARTNER_ID_HEADER); - headers.put(PARTNER_API_KEY_HEADER, PARTNER_API_KEY_HEADER); - Mockito.when(helperService.sendOTP(any(),any(),any())).thenReturn(new SendOtpResult(sendOtpDto.getTransactionId(), "", "")); - SendOtpResult sendOtpResult = idaKeyBinderImpl.sendBindingOtp("individualId", Arrays.asList("email"), headers); - Assert.assertEquals(sendOtpDto.getTransactionId(), sendOtpResult.getTransactionId()); - } - - @Test - public void sendBindingOtp_withErrorResponse_throwsException() throws Exception { - SendOtpDto sendOtpDto = new SendOtpDto(); - sendOtpDto.setIndividualId(null); - sendOtpDto.setTransactionId("4567"); - List otpChannelsList = new ArrayList<>(); - otpChannelsList.add("channel"); - sendOtpDto.setOtpChannels(otpChannelsList); - Mockito.when(helperService.sendOTP(any(),any(),any())).thenThrow(new SendOtpException("error-100")); - Map headers = new HashMap<>(); - headers.put(PARTNER_ID_HEADER, PARTNER_ID_HEADER); - headers.put(PARTNER_API_KEY_HEADER, PARTNER_API_KEY_HEADER); - try { - idaKeyBinderImpl.sendBindingOtp("individualId", Arrays.asList("email"), headers); - Assert.fail(); - } catch (SendOtpException e) { - Assert.assertEquals("error-100", e.getErrorCode()); - } - } - - @Test - public void sendBindingOtp_withEmptyHeaders_throwsException() throws Exception { - try { - idaKeyBinderImpl.sendBindingOtp("individualId", Arrays.asList("email"), new HashMap<>()); - Assert.fail(); - } catch (SendOtpException e) { - Assert.assertEquals(IdaKeyBinderImpl.REQUIRED_HEADERS_MISSING, e.getErrorCode()); - } - } - - @Test - public void doKeyBinding_withValidDetails_thenPass() throws KeyBindingException { - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - KeyBindingResponse keyBindingResponse = new KeyBindingResponse(); - keyBindingResponse.setAuthToken("auth-token"); - keyBindingResponse.setBindingAuthStatus(true); - keyBindingResponse.setIdentityCertificate("certificate"); - idaResponseWrapper.setResponse(keyBindingResponse); - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - Map headers = new HashMap<>(); - headers.put(PARTNER_ID_HEADER, PARTNER_ID_HEADER); - headers.put(PARTNER_API_KEY_HEADER, PARTNER_API_KEY_HEADER); - KeyBindingResult keyBindingResult = idaKeyBinderImpl.doKeyBinding("individualId", new ArrayList<>(), new HashMap<>(), - "WLA", headers); - Assert.assertNotNull(keyBindingResult); - Assert.assertEquals(keyBindingResponse.getAuthToken(), keyBindingResult.getPartnerSpecificUserToken()); - Assert.assertEquals(keyBindingResponse.getIdentityCertificate(), keyBindingResult.getCertificate()); - } - - @Test - public void doKeyBinding_withAuthFailure_thenPass() { - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - KeyBindingResponse keyBindingResponse = new KeyBindingResponse(); - keyBindingResponse.setAuthToken("auth-token"); - keyBindingResponse.setBindingAuthStatus(false); - keyBindingResponse.setIdentityCertificate("certificate"); - idaResponseWrapper.setResponse(keyBindingResponse); - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - Map headers = new HashMap<>(); - headers.put(PARTNER_ID_HEADER, PARTNER_ID_HEADER); - headers.put(PARTNER_API_KEY_HEADER, PARTNER_API_KEY_HEADER); - try { - idaKeyBinderImpl.doKeyBinding("individualId", new ArrayList<>(), new HashMap<>(), - "WLA", headers); - Assert.fail(); - } catch (KeyBindingException e) { - Assert.assertEquals(ErrorConstants.BINDING_AUTH_FAILED, e.getErrorCode()); - } - } - - @Test - public void doKeyBinding_withErrorResponse_thenFail() { - IdaResponseWrapper idaResponseWrapper = new IdaResponseWrapper<>(); - IdaError idaError = new IdaError(); - idaError.setErrorCode("test-err-code"); - idaResponseWrapper.setErrors(Arrays.asList(idaError)); - ResponseEntity> responseEntity = new ResponseEntity>( - idaResponseWrapper, HttpStatus.OK); - - Mockito.when(restTemplate.exchange(Mockito.>any(), - Mockito.>>any())) - .thenReturn(responseEntity); - - Map headers = new HashMap<>(); - headers.put(PARTNER_ID_HEADER, PARTNER_ID_HEADER); - headers.put(PARTNER_API_KEY_HEADER, PARTNER_API_KEY_HEADER); - try { - idaKeyBinderImpl.doKeyBinding("individualId", new ArrayList<>(), new HashMap<>(), - "WLA", headers); - Assert.fail(); - } catch (KeyBindingException e) { - Assert.assertEquals("test-err-code", e.getErrorCode()); - } - } - - @Test - public void doKeyBinding_withEmptyHeaders_thenFail() { - try { - idaKeyBinderImpl.doKeyBinding("individualId", new ArrayList<>(), new HashMap<>(), - "WLA", new HashMap<>()); - Assert.fail(); - } catch (KeyBindingException e) { - Assert.assertEquals(IdaKeyBinderImpl.REQUIRED_HEADERS_MISSING, e.getErrorCode()); - } - } -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java index fe3bb52f8c6..e69de29bb2d 100644 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java +++ b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java @@ -1,281 +0,0 @@ -package io.mosip.authentication.esignet.integration.service; - -import com.fasterxml.jackson.databind.ObjectMapper; -import foundation.identity.jsonld.JsonLDObject; -import io.mosip.authentication.esignet.integration.dto.IdaResponseWrapper; -import io.mosip.authentication.esignet.integration.dto.IdaVcExchangeRequest; -import io.mosip.authentication.esignet.integration.dto.IdaVcExchangeResponse; -import io.mosip.authentication.esignet.integration.helper.VCITransactionHelper; -import io.mosip.esignet.api.dto.VCRequestDto; -import io.mosip.esignet.api.dto.VCResult; -import io.mosip.esignet.core.constants.ErrorConstants; -import io.mosip.esignet.core.dto.OIDCTransaction; -import io.mosip.esignet.core.exception.EsignetException; -import io.mosip.esignet.core.util.IdentityProviderUtil; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; - -import javax.crypto.Cipher; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.time.LocalDateTime; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant.CURRENTKEYALIAS; - -@RunWith(MockitoJUnitRunner.class) -public class IdaVCIssuancePluginImplTest { - - @Mock - VCITransactionHelper vciTransactionHelper; - - @Mock - ObjectMapper objectMapper; - - @Mock - RestTemplate restTemplate; - - @Mock - HelperService helperService; - - @Mock - KeymanagerDBHelper keymanagerDBHelper; - - @Mock - KeyStore keyStore; - - @InjectMocks - IdaVCIssuancePluginImpl idaVCIssuancePlugin=new IdaVCIssuancePluginImpl(); - - @Test - public void getVerifiableCredentialWithLinkedDataProof_withValidDetails_thenPass() throws Exception { - - ReflectionTestUtils.setField(idaVCIssuancePlugin,"vciExchangeUrl","http://example.com"); - - VCRequestDto vcRequestDto = new VCRequestDto(); - vcRequestDto.setFormat("ldp_vc"); - vcRequestDto.setContext(Arrays.asList("context1","context2")); - vcRequestDto.setType(Arrays.asList("VerifiableCredential")); - vcRequestDto.setCredentialSubject(Map.of("subject1","subject1","subject2","subject2")); - - OIDCTransaction oidcTransaction = new OIDCTransaction(); - oidcTransaction.setIndividualId("individualId"); - oidcTransaction.setKycToken("kycToken"); - oidcTransaction.setAuthTransactionId("authTransactionId"); - oidcTransaction.setRelyingPartyId("relyingPartyId"); - oidcTransaction.setClaimsLocales(new String[]{"en-US", "en", "en-CA", "fr-FR", "fr-CA"}); - - IdaResponseWrapper> mockResponseWrapper = new IdaResponseWrapper<>(); - IdaVcExchangeResponse mockResponse = new IdaVcExchangeResponse<>(); - JsonLDObject jsonLDObject = new JsonLDObject(); - jsonLDObject.setJsonObjectKeyValue("key", "value"); - mockResponse.setVerifiableCredentials(jsonLDObject); - mockResponseWrapper.setResponse(mockResponse); - mockResponseWrapper.setId("id"); - mockResponseWrapper.setVersion("version"); - mockResponseWrapper.setTransactionID("transactionID"); - - ResponseEntity>> mockResponseEntity = ResponseEntity.ok(mockResponseWrapper); - ParameterizedTypeReference>> responseType = - new ParameterizedTypeReference>>() { - }; - - Mockito.when(vciTransactionHelper.getOAuthTransaction(Mockito.any())).thenReturn(oidcTransaction); - Mockito.when(objectMapper.writeValueAsString(Mockito.any(IdaVcExchangeRequest.class))).thenReturn("jsonString"); - Mockito.when(restTemplate.exchange( - Mockito.any(RequestEntity.class), - Mockito.eq(responseType) - )).thenReturn(mockResponseEntity); - - VCResult result=idaVCIssuancePlugin.getVerifiableCredentialWithLinkedDataProof(vcRequestDto,"holderId",Map.of("accessTokenHash","ACCESS_TOKEN_HASH","client_id","CLIENT_ID")); - Assert.assertNotNull(result.getCredential()); - Assert.assertEquals(jsonLDObject,result.getCredential()); - Assert.assertEquals(result.getFormat(),"ldp_vc"); - } - - @Test - public void getVerifiableCredentialWithLinkedDataProof_withValidDetailsAndStoreIndividualId_thenPass() throws Exception { - - ReflectionTestUtils.setField(idaVCIssuancePlugin,"vciExchangeUrl","http://example.com"); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"storeIndividualId",true); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"secureIndividualId",true); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"aesECBTransformation","AES/ECB/PKCS5Padding"); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"cacheSecretKeyRefId","cacheSecretKeyRefId"); - - VCRequestDto vcRequestDto = new VCRequestDto(); - vcRequestDto.setFormat("ldp_vc"); - vcRequestDto.setContext(Arrays.asList("context1","context2")); - vcRequestDto.setType(Arrays.asList("VerifiableCredential")); - vcRequestDto.setCredentialSubject(Map.of("subject1","subject1","subject2","subject2")); - - KeyGenerator generator = KeyGenerator.getInstance("AES"); - generator.init(256); - SecretKey key = generator.generateKey(); - String individualId = encryptIndividualId("individual-id",key); - - OIDCTransaction oidcTransaction = new OIDCTransaction(); - oidcTransaction.setIndividualId(individualId); - oidcTransaction.setKycToken("kycToken"); - oidcTransaction.setAuthTransactionId("authTransactionId"); - oidcTransaction.setRelyingPartyId("relyingPartyId"); - - Map> keyaliasesMap = new HashMap<>(); - KeyAlias keyAlias = new KeyAlias(); - keyAlias.setAlias("test"); - keyaliasesMap.put(CURRENTKEYALIAS, Arrays.asList(keyAlias)); - Mockito.when(keymanagerDBHelper.getKeyAliases(Mockito.anyString(), Mockito.anyString(), Mockito.any(LocalDateTime.class))).thenReturn(keyaliasesMap); - Mockito.when(keyStore.getSymmetricKey(Mockito.anyString())).thenReturn(key, key); - - IdaResponseWrapper> mockResponseWrapper = new IdaResponseWrapper<>(); - IdaVcExchangeResponse mockResponse = new IdaVcExchangeResponse<>(); - JsonLDObject jsonLDObject = new JsonLDObject(); - jsonLDObject.setJsonObjectKeyValue("key", "value"); - mockResponse.setVerifiableCredentials(jsonLDObject); - mockResponseWrapper.setResponse(mockResponse); - mockResponseWrapper.setId("id"); - mockResponseWrapper.setVersion("version"); - mockResponseWrapper.setTransactionID("transactionID"); - - ResponseEntity>> mockResponseEntity = ResponseEntity.ok(mockResponseWrapper); - ParameterizedTypeReference>> responseType = - new ParameterizedTypeReference>>() { - }; - - Mockito.when(vciTransactionHelper.getOAuthTransaction(Mockito.any())).thenReturn(oidcTransaction); - Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn("jsonString"); - Mockito.when(restTemplate.exchange( - Mockito.any(RequestEntity.class), - Mockito.eq(responseType) - )).thenReturn(mockResponseEntity); - - VCResult result=idaVCIssuancePlugin.getVerifiableCredentialWithLinkedDataProof(vcRequestDto,"holderId",Map.of("accessTokenHash","ACCESS_TOKEN_HASH","client_id","CLIENT_ID")); - Assert.assertNotNull(result.getCredential()); - Assert.assertEquals(jsonLDObject,result.getCredential()); - Assert.assertEquals(result.getFormat(),"ldp_vc"); - Mockito.verify(keymanagerDBHelper).getKeyAliases(Mockito.anyString(), Mockito.anyString(), Mockito.any(LocalDateTime.class)); - } - - @Test - public void getVerifiableCredentialWithLinkedDataProof_withInValidIndividualId_thenFail() throws Exception { - - ReflectionTestUtils.setField(idaVCIssuancePlugin,"vciExchangeUrl","http://example.com"); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"storeIndividualId",true); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"secureIndividualId",true); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"aesECBTransformation","AES/ECB/PKCS5Padding"); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"cacheSecretKeyRefId","cacheSecretKeyRefId"); - - VCRequestDto vcRequestDto = new VCRequestDto(); - vcRequestDto.setFormat("ld_vc"); - vcRequestDto.setContext(Arrays.asList("context1","context2")); - vcRequestDto.setType(Arrays.asList("VerifiableCredential")); - vcRequestDto.setCredentialSubject(Map.of("subject1","subject1","subject2","subject2")); - - OIDCTransaction oidcTransaction = new OIDCTransaction(); - oidcTransaction.setIndividualId("individualId"); - oidcTransaction.setKycToken("kycToken"); - oidcTransaction.setAuthTransactionId("authTransactionId"); - oidcTransaction.setRelyingPartyId("relyingPartyId"); - - Mockito.when(vciTransactionHelper.getOAuthTransaction(Mockito.any())).thenReturn(oidcTransaction); - try{ - VCResult result= idaVCIssuancePlugin.getVerifiableCredentialWithLinkedDataProof(vcRequestDto,"holderId",Map.of("accessTokenHash","ACCESS_TOKEN_HASH","client_id","CLIENT_ID")); - Assert.fail(); - }catch (Exception e) - { - Assert.assertEquals("vci_exchange_failed",e.getMessage()); - } - } - - @Test - public void getVerifiableCredentialWithLinkedDataProof_withInVlidResponse_thenFail() throws Exception { - - ReflectionTestUtils.setField(idaVCIssuancePlugin,"vciExchangeUrl","http://example.com"); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"storeIndividualId",true); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"secureIndividualId",true); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"aesECBTransformation","AES/ECB/PKCS5Padding"); - ReflectionTestUtils.setField(idaVCIssuancePlugin,"cacheSecretKeyRefId","cacheSecretKeyRefId"); - - VCRequestDto vcRequestDto = new VCRequestDto(); - vcRequestDto.setFormat("ldp_vc"); - vcRequestDto.setContext(Arrays.asList("context1","context2")); - vcRequestDto.setType(Arrays.asList("VerifiableCredential")); - vcRequestDto.setCredentialSubject(Map.of("subject1","subject1","subject2","subject2")); - - KeyGenerator generator = KeyGenerator.getInstance("AES"); - generator.init(256); - SecretKey key = generator.generateKey(); - String individualId = encryptIndividualId("individual-id",key); - - OIDCTransaction oidcTransaction = new OIDCTransaction(); - oidcTransaction.setIndividualId(individualId); - oidcTransaction.setKycToken("kycToken"); - oidcTransaction.setAuthTransactionId("authTransactionId"); - oidcTransaction.setRelyingPartyId("relyingPartyId"); - - Map> keyaliasesMap = new HashMap<>(); - KeyAlias keyAlias = new KeyAlias(); - keyAlias.setAlias("test"); - keyaliasesMap.put(CURRENTKEYALIAS, Arrays.asList(keyAlias)); - Mockito.when(vciTransactionHelper.getOAuthTransaction(Mockito.any())).thenReturn(oidcTransaction); - Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn("jsonString"); - Mockito.when(keymanagerDBHelper.getKeyAliases(Mockito.anyString(), Mockito.anyString(), Mockito.any(LocalDateTime.class))).thenReturn(keyaliasesMap); - Mockito.when(keyStore.getSymmetricKey(Mockito.anyString())).thenReturn(key, key); - - IdaResponseWrapper> mockResponseWrapper = new IdaResponseWrapper<>(); - IdaVcExchangeResponse mockResponse = new IdaVcExchangeResponse<>(); - JsonLDObject jsonLDObject = new JsonLDObject(); - jsonLDObject.setJsonObjectKeyValue("key", "value"); - mockResponse.setVerifiableCredentials(jsonLDObject); - mockResponseWrapper.setResponse(null); - mockResponseWrapper.setId("id"); - mockResponseWrapper.setVersion("version"); - mockResponseWrapper.setTransactionID("transactionID"); - - ResponseEntity>> mockResponseEntity = ResponseEntity.ok(mockResponseWrapper); - ParameterizedTypeReference>> responseType = - new ParameterizedTypeReference>>() { - }; - Mockito.when(restTemplate.exchange( - Mockito.any(RequestEntity.class), - Mockito.eq(responseType) - )).thenReturn(mockResponseEntity); - - try{ - VCResult result= idaVCIssuancePlugin.getVerifiableCredentialWithLinkedDataProof(vcRequestDto,"holderId",Map.of("accessTokenHash","ACCESS_TOKEN_HASH","client_id","CLIENT_ID")); - Assert.fail(); - }catch (Exception e) - { - Assert.assertEquals("vci_exchange_failed",e.getMessage()); - } - } - - private String encryptIndividualId(String individualId, Key key) { - try { - Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); - byte[] secretDataBytes = individualId.getBytes(StandardCharsets.UTF_8); - cipher.init(Cipher.ENCRYPT_MODE,key); - return IdentityProviderUtil.b64Encode(cipher.doFinal(secretDataBytes, 0, secretDataBytes.length)); - } catch(Exception e) { - throw new EsignetException(ErrorConstants.AES_CIPHER_FAILED); - } - } - -} diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/TestUtil.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/TestUtil.java deleted file mode 100644 index 9d0becf24cb..00000000000 --- a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/TestUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. - */ -package io.mosip.authentication.esignet.integration.service; - -import java.math.BigInteger; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Date; -import java.util.UUID; - - -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.KeyUse; -import com.nimbusds.jose.jwk.RSAKey; - -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.x509.X509V3CertificateGenerator; - -import javax.security.auth.x500.X500Principal; - -@Slf4j -public class TestUtil { - - public static JWK generateJWK_RSA() { - // Generate the RSA key pair - try { - KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); - gen.initialize(2048); - KeyPair keyPair = gen.generateKeyPair(); - // Convert public key to JWK format - return new RSAKey.Builder((RSAPublicKey)keyPair.getPublic()) - .privateKey((RSAPrivateKey)keyPair.getPrivate()) - .keyUse(KeyUse.SIGNATURE) - .keyID(UUID.randomUUID().toString()) - .build(); - } catch (NoSuchAlgorithmException e) { - log.error("generateJWK_RSA failed", e); - } - return null; - } - - public static X509Certificate getCertificate() throws Exception { - JWK clientJWK = TestUtil.generateJWK_RSA(); - X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); - X500Principal dnName = new X500Principal("CN=Test"); - generator.setSubjectDN(dnName); - generator.setIssuerDN(dnName); // use the same - generator.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000)); - generator.setNotAfter(new Date(System.currentTimeMillis() + 24 * 365 * 24 * 60 * 60 * 1000)); - generator.setPublicKey(clientJWK.toRSAKey().toPublicKey()); - generator.setSignatureAlgorithm("SHA256WITHRSA"); - generator.setSerialNumber(new BigInteger(String.valueOf(System.currentTimeMillis()))); - return generator.generate(clientJWK.toRSAKey().toPrivateKey()); - } - - public static X509Certificate getExpiredCertificate() throws Exception { - JWK clientJWK = TestUtil.generateJWK_RSA(); - X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); - X500Principal dnName = new X500Principal("CN=Test"); - generator.setSubjectDN(dnName); - generator.setIssuerDN(dnName); // use the same - generator.setNotBefore(new Date(System.currentTimeMillis())); - generator.setNotAfter(new Date(System.currentTimeMillis())); - generator.setPublicKey(clientJWK.toRSAKey().toPublicKey()); - generator.setSignatureAlgorithm("SHA256WITHRSA"); - generator.setSerialNumber(new BigInteger(String.valueOf(System.currentTimeMillis()))); - return generator.generate(clientJWK.toRSAKey().toPrivateKey()); - } -} diff --git a/authentication/pom.xml b/authentication/pom.xml index 447e74c6748..1f5b0f75473 100644 --- a/authentication/pom.xml +++ b/authentication/pom.xml @@ -105,15 +105,15 @@ ${kernel.parent.version} ${kernel.parent.version} ${kernel.parent.version} - 1.2.0.1 + ${kernel.parent.version} ${kernel.parent.version} ${kernel.parent.version} - 1.2.0.1 + 1.2.0.1-B1 20180130 1.2.0.1 ${kernel.parent.version} ${kernel.parent.version} - 1.2.0.1 + ${kernel.parent.version} 11 @@ -422,7 +422,7 @@ true - ${project.build.outputDirectory}/git.properties + ${project.build.outputDirectory}/service-git.properties ^git.build.(time|version)$ ^git.commit.id.(abbrev|full)$ From 30ada905fbe615f6e2a19066eea3114a9078b730 Mon Sep 17 00:00:00 2001 From: dhanendra06 Date: Thu, 22 Aug 2024 16:27:48 +0530 Subject: [PATCH 9/9] resolved the conflict for MOSIP-32162 Signed-off-by: dhanendra06 --- authentication/esignet-integration-impl/pom.xml | 0 .../esignet/integration/service/HelperService.java | 0 .../esignet/integration/service/IdaAuditPluginImpl.java | 0 .../esignet/integration/service/IdaAuthenticatorImpl.java | 0 .../esignet/integration/service/IdaKeyBinderImpl.java | 0 .../esignet/integration/service/IdaAuditPluginImplTest.java | 0 .../esignet/integration/service/IdaKeyBinderImplTest.java | 0 .../esignet/integration/service/IdaVCIssuancePluginImplTest.java | 0 authentication/pom.xml | 1 - 9 files changed, 1 deletion(-) delete mode 100644 authentication/esignet-integration-impl/pom.xml delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImpl.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java delete mode 100644 authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java delete mode 100644 authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java diff --git a/authentication/esignet-integration-impl/pom.xml b/authentication/esignet-integration-impl/pom.xml deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/HelperService.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImpl.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaAuthenticatorImpl.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImpl.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaKeyBinderImplTest.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/authentication/pom.xml b/authentication/pom.xml index 1f5b0f75473..cb42bca4acf 100644 --- a/authentication/pom.xml +++ b/authentication/pom.xml @@ -80,7 +80,6 @@ authentication-service authentication-internal-service authentication-otp-service - esignet-integration-impl