diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index da2a570e147..a460d425a99 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -43,7 +43,7 @@ jobs: secrets: OSSRH_USER: ${{ secrets.OSSRH_USER }} OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_URL: ${{ secrets.RELEASE_URL }} + OSSRH_URL: ${{ secrets.OSSRH_SNAPSHOT_URL }} OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} GPG_SECRET: ${{ secrets.GPG_SECRET }} SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} diff --git a/authentication/authentication-authtypelockfilter-impl/pom.xml b/authentication/authentication-authtypelockfilter-impl/pom.xml index c5bacf60c3f..ae96c9ee7be 100644 --- a/authentication/authentication-authtypelockfilter-impl/pom.xml +++ b/authentication/authentication-authtypelockfilter-impl/pom.xml @@ -4,9 +4,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-authtypelockfilter-impl authentication-authtypelockfilter-impl ID Authentication Filter Implementation for Auth Type Lock validation diff --git a/authentication/authentication-common/pom.xml b/authentication/authentication-common/pom.xml index 4b1774112ed..b2b005e83d4 100644 --- a/authentication/authentication-common/pom.xml +++ b/authentication/authentication-common/pom.xml @@ -6,9 +6,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-common authentication-common diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java index b2f00b47101..3117ec4c3fc 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java @@ -126,4 +126,7 @@ public class IDAMappingConfig implements MappingConfig { /** The dynamic attributes. */ private Map> dynamicAttributes; + /** The password. */ + private List password; + } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java index e215a10e3a8..3a3b27878cf 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java @@ -29,6 +29,7 @@ import io.mosip.authentication.common.service.helper.AuditHelper; import io.mosip.authentication.common.service.helper.AuthTransactionHelper; import io.mosip.authentication.common.service.helper.IdInfoHelper; +import io.mosip.authentication.common.service.impl.match.IdaIdMapping; import io.mosip.authentication.common.service.integration.TokenIdManager; import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; import io.mosip.authentication.common.service.util.AuthTypeUtil; @@ -47,6 +48,7 @@ import io.mosip.authentication.core.indauth.dto.AuthStatusInfo; import io.mosip.authentication.core.indauth.dto.IdType; import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; +import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO; import io.mosip.authentication.core.indauth.dto.EkycAuthRequestDTO; import io.mosip.authentication.core.logger.IdaLogger; import io.mosip.authentication.core.partner.dto.PartnerPolicyResponseDTO; @@ -58,6 +60,7 @@ import io.mosip.authentication.core.spi.indauth.service.BioAuthService; import io.mosip.authentication.core.spi.indauth.service.DemoAuthService; import io.mosip.authentication.core.spi.indauth.service.OTPAuthService; +import io.mosip.authentication.core.spi.indauth.service.PasswordAuthService; import io.mosip.authentication.core.spi.notification.service.NotificationService; import io.mosip.authentication.core.spi.partner.service.PartnerService; import io.mosip.kernel.core.logger.spi.Logger; @@ -129,6 +132,9 @@ public class AuthFacadeImpl implements AuthFacade { @Autowired private KeyBindedTokenAuthService keyBindedTokenAuthService; + + @Autowired + private PasswordAuthService passwordAuthService; /* * (non-Javadoc) @@ -161,6 +167,14 @@ public AuthResponseDTO authenticateIndividual(AuthRequestDTO authRequestDTO, boo addKycPolicyAttributes(filterAttributes, kycAuthRequestDTO); } + + if(authRequestDTO instanceof KycAuthRequestDTO) { + KycAuthRequestDTO kycAuthRequestDTO = (KycAuthRequestDTO) authRequestDTO; + // In case of kyc-auth request and password auth is requested + if(AuthTypeUtil.isPassword(kycAuthRequestDTO)) { + filterAttributes.add(IdaIdMapping.PASSWORD.getIdname()); + } + } Map idResDTO = idService.processIdType(idvIdType, idvid, idInfoHelper.isBiometricDataNeeded(authRequestDTO), markVidConsumed, filterAttributes); @@ -312,6 +326,11 @@ private List processAuthType(AuthRequestDTO authRequestDTO, authTxnBuilder, idvidHash); } + if (!isMatchFailed(authStatusList)) { + processPasswordAuth(authRequestDTO, idInfo, token, isAuth, authStatusList, idType, authTokenId, partnerId, + authTxnBuilder, idvidHash); + } + return authStatusList; } @@ -383,7 +402,7 @@ private void processDemoAuth(AuthRequestDTO authRequestDTO, Map> idInfo, String token, + boolean isAuth, List authStatusList, IdType idType, String authTokenId, String partnerId, + AuthTransactionBuilder authTxnBuilder, String idvidHash) throws IdAuthenticationBusinessException { + if (AuthTypeUtil.isPassword(authRequestDTO)) { + AuthStatusInfo passwordMatchStatus = null; + try { + passwordMatchStatus = passwordAuthService.authenticate(authRequestDTO, token, idInfo, partnerId); + authStatusList.add(passwordMatchStatus); + + boolean isStatus = passwordMatchStatus != null && passwordMatchStatus.isStatus(); + auditHelper.audit(AuditModules.PASSWORD_AUTH, AuditEvents.PASSWORD_BASED_AUTH_REQUEST, authRequestDTO.getTransactionID(), + idType, "authenticateApplicant status(Password) : " + isStatus); + } finally { + boolean isStatus = passwordMatchStatus != null && passwordMatchStatus.isStatus(); + logger.info(IdAuthCommonConstants.SESSION_ID, EnvUtil.getAppId(), + AUTH_FACADE, "Password Authentication status : " + isStatus); + authTxnBuilder.addRequestType(RequestType.PASSWORD_AUTH); + } + } + } } \ No newline at end of file diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java index 55bf6f085b6..f74ad9f18d8 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java @@ -465,6 +465,12 @@ protected String consumeResponse(ResettableStreamHttpServletRequest requestWrapp String requestSignature = requestWrapper.getHeader(SIGNATURE); String responseSignature = null; if(isSigningRequired()) { + if (Objects.isNull(responseAsString) || responseAsString.trim().length() == 0) { + mosipLogger.error(IdAuthCommonConstants.SESSION_ID, EVENT_FILTER, BASE_IDA_FILTER, + " Response String is null or empty for response (JWT) signing"); + throw new IdAuthenticationAppException(IdAuthenticationErrorConstants.UNABLE_TO_PROCESS.getErrorCode(), + IdAuthenticationErrorConstants.UNABLE_TO_PROCESS.getErrorMessage()); + } responseSignature = keyManager.signResponse(responseAsString); responseWrapper.setHeader(EnvUtil.getSignResponse(), responseSignature); } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java index 10b4c712394..e9a162fac2c 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java @@ -28,6 +28,8 @@ import javax.servlet.ServletException; import io.mosip.authentication.core.indauth.dto.KeyBindedTokenDTO; +import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO; + import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -843,6 +845,7 @@ protected void checkAllowedAuthTypeForKeyBindedToken(Map request Object value = Optional.ofNullable(requestBody.get(IdAuthCommonConstants.REQUEST)) .filter(obj -> obj instanceof Map).map(obj -> ((Map) obj).get(KEY_BINDED_TOKEN)) .filter(obj -> obj instanceof List).orElse(Collections.emptyMap()); + List list = mapper.readValue(mapper.writeValueAsBytes(value), new TypeReference>() { }); @@ -861,6 +864,19 @@ protected void checkAllowedAuthTypeForKeyBindedToken(Map request } } + protected void checkAllowedAuthTypeForPassword(Map requestBody, List authPolicies) + throws IdAuthenticationAppException, IOException { + KycAuthRequestDTO authRequestDTO = mapper.readValue(mapper.writeValueAsBytes(requestBody), + KycAuthRequestDTO.class); + + if (AuthTypeUtil.isPassword(authRequestDTO) && !isAllowedAuthType(MatchType.Category.PWD.getType(), authPolicies)) { + throw new IdAuthenticationAppException( + IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorCode(), + String.format(IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorMessage(), + MatchType.Category.PWD.name())); + } + } + /** * Check allowed auth type for bio. * @@ -1042,16 +1058,25 @@ private void checkAllowedAMRBasedOnClientConfig(Map requestBody, if (AuthTypeUtil.isPin(authRequestDTO) && !allowedAMRs.contains(MatchType.Category.SPIN.getType())) { throw new IdAuthenticationAppException( - IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorCode(), - String.format(IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorMessage(), + IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorCode(), + String.format(IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorMessage(), MatchType.Category.SPIN.name())); } if (AuthTypeUtil.isOtp(authRequestDTO) && !allowedAMRs.contains(MatchType.Category.OTP.getType())) { throw new IdAuthenticationAppException( - IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorCode(), - String.format(IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorMessage(), + IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorCode(), + String.format(IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorMessage(), MatchType.Category.OTP.name())); } + + KycAuthRequestDTO kycAuthRequestDTO = mapper.readValue(mapper.writeValueAsBytes(requestBody), + KycAuthRequestDTO.class); + if (AuthTypeUtil.isPassword(kycAuthRequestDTO) && !allowedAMRs.contains(MatchType.Category.PWD.getType())) { + throw new IdAuthenticationAppException( + IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorCode(), + String.format(IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorMessage(), + MatchType.Category.PWD.name())); + } checkAllowedAMRForKBT(requestBody, allowedAMRs); } } catch (IOException e) { @@ -1119,19 +1144,28 @@ private Set getAuthenticationFactors(PartnerPolicyResponseDTO partnerPol * @param requestWrapper the request wrapper * @return the auth part */ - protected Map getAuthPart(ResettableStreamHttpServletRequest requestWrapper) { + protected Map getAuthPart(ResettableStreamHttpServletRequest requestWrapper) throws IdAuthenticationAppException{ Map params = new HashMap<>(); String url = requestWrapper.getRequestURL().toString(); String contextPath = requestWrapper.getContextPath(); if ((Objects.nonNull(url) && !url.isEmpty()) && (Objects.nonNull(contextPath) && !contextPath.isEmpty())) { String[] splitedUrlByContext = url.split(contextPath); String[] paramsArray = Stream.of(splitedUrlByContext[1].split("/")).filter(str -> !str.isEmpty()) - .toArray(size -> new String[size]); + .toArray(size -> new String[size]); + mosipLogger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getCanonicalName(), "getAuthPart", + "List of Path Parameters received in url: " + Stream.of(paramsArray).collect(Collectors.joining(", "))); if (paramsArray.length >= 3) { params.put(MISPLICENSE_KEY, paramsArray[paramsArray.length - 3]); params.put(PARTNER_ID, paramsArray[paramsArray.length - 2]); params.put(API_KEY, paramsArray[paramsArray.length - 1]); + } else { + mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getCanonicalName(), "getAuthPart", + "Required Number of Path Parameters are not available in URL."); + throw new IdAuthenticationAppException( + IdAuthenticationErrorConstants.URI_PATH_PARAMS_MISSING.getErrorCode(), + IdAuthenticationErrorConstants.URI_PATH_PARAMS_MISSING.getErrorMessage()); + } } return params; diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java index 55c9edc9189..bb22b52a9db 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java @@ -1,188 +1,196 @@ -package io.mosip.authentication.common.service.helper; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.authentication.common.service.exception.IdAuthExceptionHandler; -import io.mosip.authentication.common.service.factory.AuditRequestFactory; -import io.mosip.authentication.common.service.factory.RestRequestFactory; -import io.mosip.authentication.common.service.impl.match.BioAuthType; -import io.mosip.authentication.common.service.util.AuthTypeUtil; -import io.mosip.authentication.common.service.util.EnvUtil; -import io.mosip.authentication.core.constant.AuditEvents; -import io.mosip.authentication.core.constant.AuditModules; -import io.mosip.authentication.core.constant.RestServicesConstants; -import io.mosip.authentication.core.dto.AuditRequestDto; -import io.mosip.authentication.core.exception.IDDataValidationException; -import io.mosip.authentication.core.exception.IdAuthenticationBaseException; -import io.mosip.authentication.core.indauth.dto.AuthError; -import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; -import io.mosip.authentication.core.indauth.dto.BioIdentityInfoDTO; -import io.mosip.authentication.core.indauth.dto.IdType; -import io.mosip.idrepository.core.dto.RestRequestDTO; -import io.mosip.idrepository.core.helper.RestHelper; -import io.mosip.kernel.core.http.RequestWrapper; - -/** - * The Class AuditHelper - build audit requests and send it to audit service. - * - * @author Manoj SP - */ -@Component -public class AuditHelper { - - /** The rest helper. */ - @Autowired - @Qualifier("withSelfTokenWebclient") - private RestHelper restHelper; - - /** The audit factory. */ - @Autowired - private AuditRequestFactory auditFactory; - - /** The rest factory. */ - @Autowired - private RestRequestFactory restFactory; - - @Autowired - private ObjectMapper mapper; - - /** The EnvPropertyResolver */ - @Autowired - private EnvUtil env; - - - /** - * Method to build audit requests and send it to audit service. - * - * @param module {@link AuditModules} - * @param event {@link AuditEvents} - * @param id UIN/VID - * @param idType {@link IdType} enum - * @param desc the desc - * @throws IDDataValidationException the ID data validation exception - */ - public void audit(AuditModules module, AuditEvents event, String id, IdType idType, String desc) - throws IDDataValidationException { - audit(module, event, id, idType.name(), desc); - } - - /** - * Method to build audit requests and send it to audit service. - * - * @param module {@link AuditModules} - * @param event {@link AuditEvents} - * @param id UIN/VID - * @param idType {@link IdType} name - * @param desc the desc - * @throws IDDataValidationException the ID data validation exception - */ - public void audit(AuditModules module, AuditEvents event, String id, String idType, String desc) - throws IDDataValidationException { - RequestWrapper auditRequest = auditFactory.buildRequest(module, event, id, idType, desc); - RestRequestDTO restRequest = restFactory.buildRequest(RestServicesConstants.AUDIT_MANAGER_SERVICE, auditRequest, - Map.class); - restHelper.requestAsync(restRequest); - } - - /** - * Method to build audit error scenarios and send it to audit service. - * - * @param module {@link AuditModules} - * @param event {@link AuditEvents} - * @param id UIN/VID - * @param idType {@link IdType} enum - * @param desc the desc - * @throws IDDataValidationException the ID data validation exception - */ - public void audit(AuditModules module, AuditEvents event, String id, IdType idType, IdAuthenticationBaseException e) - throws IDDataValidationException { - audit(module, event, id, idType.name(), e); - } - - /** - * Method to build audit error scenarios and send it to audit service. - * - * @param module {@link AuditModules} - * @param event {@link AuditEvents} - * @param id UIN/VID - * @param idType {@link IdType} name - * @param desc the desc - * @throws IDDataValidationException the ID data validation exception - */ - public void audit(AuditModules module, AuditEvents event, String id, String idType, IdAuthenticationBaseException e) - throws IDDataValidationException { - List errorList = IdAuthExceptionHandler.getAuthErrors(e); - String error; - try { - error = mapper.writeValueAsString(errorList); - } catch (JsonProcessingException e1) { - //Probably will not occur - error = "Error : " + e.getErrorCode() + " - " + e.getErrorText(); - } - audit(module, event, id, idType, error); - } - - public void auditExceptionForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO, - IdAuthenticationBaseException e) throws IDDataValidationException { - List auditModules = getAuditModules(authRequestDTO); - for (AuditModules auditModule : auditModules) { - audit(auditModule, authAuditEvent, authRequestDTO.getIndividualId(), authRequestDTO.getIndividualIdType(), - e); - } - } - - public void auditStatusForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO, - String status) throws IDDataValidationException { - List auditModules = getAuditModules(authRequestDTO); - for (AuditModules auditModule : auditModules) { - audit(auditModule, authAuditEvent, authRequestDTO.getIndividualId(), authRequestDTO.getIndividualIdType(), - status); - } - } - - private List getAuditModules(AuthRequestDTO authRequestDTO) { - List auditModules = new ArrayList<>(5); - if (AuthTypeUtil.isOtp(authRequestDTO)) { - auditModules.add(AuditModules.OTP_AUTH); - } - - if (AuthTypeUtil.isDemo(authRequestDTO)) { - auditModules.add(AuditModules.DEMO_AUTH); - } - - if (AuthTypeUtil.isPin(authRequestDTO)) { - auditModules.add(AuditModules.PIN_AUTH); - } - - if (AuthTypeUtil.isBio(authRequestDTO)) { - if (authRequestDTO.getRequest() != null && authRequestDTO.getRequest().getBiometrics() != null) { - if ((authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData).anyMatch( - bioInfo -> BioAuthType.FGR_IMG.getType().equals(bioInfo.getBioType()) || (EnvUtil.getIsFmrEnabled() - && BioAuthType.FGR_MIN.getType().equals(bioInfo.getBioType()))))) { - auditModules.add(AuditModules.FINGERPRINT_AUTH); - } - - if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData) - .anyMatch(bioInfo -> BioAuthType.IRIS_IMG.getType().equals(bioInfo.getBioType()))) { - auditModules.add(AuditModules.IRIS_AUTH); - } - - if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData) - .anyMatch(bioInfo -> BioAuthType.FACE_IMG.getType().equals(bioInfo.getBioType()))) { - auditModules.add(AuditModules.FACE_AUTH); - } - } - } - return auditModules; - } - -} +package io.mosip.authentication.common.service.helper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.authentication.common.service.exception.IdAuthExceptionHandler; +import io.mosip.authentication.common.service.factory.AuditRequestFactory; +import io.mosip.authentication.common.service.factory.RestRequestFactory; +import io.mosip.authentication.common.service.impl.match.BioAuthType; +import io.mosip.authentication.common.service.util.AuthTypeUtil; +import io.mosip.authentication.common.service.util.EnvUtil; +import io.mosip.authentication.core.constant.AuditEvents; +import io.mosip.authentication.core.constant.AuditModules; +import io.mosip.authentication.core.constant.RestServicesConstants; +import io.mosip.authentication.core.dto.AuditRequestDto; +import io.mosip.authentication.core.exception.IDDataValidationException; +import io.mosip.authentication.core.exception.IdAuthenticationBaseException; +import io.mosip.authentication.core.indauth.dto.AuthError; +import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; +import io.mosip.authentication.core.indauth.dto.BioIdentityInfoDTO; +import io.mosip.authentication.core.indauth.dto.IdType; +import io.mosip.idrepository.core.dto.RestRequestDTO; +import io.mosip.idrepository.core.helper.RestHelper; +import io.mosip.kernel.core.http.RequestWrapper; + +/** + * The Class AuditHelper - build audit requests and send it to audit service. + * + * @author Manoj SP + */ +@Component +public class AuditHelper { + + /** The rest helper. */ + @Autowired + @Qualifier("withSelfTokenWebclient") + private RestHelper restHelper; + + /** The audit factory. */ + @Autowired + private AuditRequestFactory auditFactory; + + /** The rest factory. */ + @Autowired + private RestRequestFactory restFactory; + + @Autowired + private ObjectMapper mapper; + + /** The EnvPropertyResolver */ + @Autowired + private EnvUtil env; + + + /** + * Method to build audit requests and send it to audit service. + * + * @param module {@link AuditModules} + * @param event {@link AuditEvents} + * @param id UIN/VID + * @param idType {@link IdType} enum + * @param desc the desc + * @throws IDDataValidationException the ID data validation exception + */ + public void audit(AuditModules module, AuditEvents event, String id, IdType idType, String desc) + throws IDDataValidationException { + audit(module, event, id, idType.name(), desc); + } + + /** + * Method to build audit requests and send it to audit service. + * + * @param module {@link AuditModules} + * @param event {@link AuditEvents} + * @param id UIN/VID + * @param idType {@link IdType} name + * @param desc the desc + * @throws IDDataValidationException the ID data validation exception + */ + public void audit(AuditModules module, AuditEvents event, String id, String idType, String desc) + throws IDDataValidationException { + RequestWrapper auditRequest = auditFactory.buildRequest(module, event, id, idType, desc); + RestRequestDTO restRequest = restFactory.buildRequest(RestServicesConstants.AUDIT_MANAGER_SERVICE, auditRequest, + Map.class); + restHelper.requestAsync(restRequest); + } + + /** + * Method to build audit error scenarios and send it to audit service. + * + * @param module {@link AuditModules} + * @param event {@link AuditEvents} + * @param id UIN/VID + * @param idType {@link IdType} enum + * @param desc the desc + * @throws IDDataValidationException the ID data validation exception + */ + public void audit(AuditModules module, AuditEvents event, String id, IdType idType, IdAuthenticationBaseException e) + throws IDDataValidationException { + audit(module, event, id, idType.name(), e); + } + + /** + * Method to build audit error scenarios and send it to audit service. + * + * @param module {@link AuditModules} + * @param event {@link AuditEvents} + * @param id UIN/VID + * @param idType {@link IdType} name + * @param desc the desc + * @throws IDDataValidationException the ID data validation exception + */ + public void audit(AuditModules module, AuditEvents event, String id, String idType, IdAuthenticationBaseException e) + throws IDDataValidationException { + List errorList = IdAuthExceptionHandler.getAuthErrors(e); + String error; + try { + error = mapper.writeValueAsString(errorList); + } catch (JsonProcessingException e1) { + //Probably will not occur + error = "Error : " + e.getErrorCode() + " - " + e.getErrorText(); + } + audit(module, event, id, idType, error); + } + + public void auditExceptionForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO, + IdAuthenticationBaseException e) throws IDDataValidationException { + List auditModules = getAuditModules(authRequestDTO); + for (AuditModules auditModule : auditModules) { + audit(auditModule, authAuditEvent, authRequestDTO.getTransactionID(), authRequestDTO.getIndividualIdType(), + e); + } + } + + public void auditStatusForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO, + String status) throws IDDataValidationException { + List auditModules = getAuditModules(authRequestDTO); + for (AuditModules auditModule : auditModules) { + audit(auditModule, authAuditEvent, authRequestDTO.getTransactionID(), authRequestDTO.getIndividualIdType(), + status); + } + } + + private List getAuditModules(AuthRequestDTO authRequestDTO) { + List auditModules = new ArrayList<>(5); + if (AuthTypeUtil.isOtp(authRequestDTO)) { + auditModules.add(AuditModules.OTP_AUTH); + } + + if (AuthTypeUtil.isDemo(authRequestDTO)) { + auditModules.add(AuditModules.DEMO_AUTH); + } + + if (AuthTypeUtil.isPin(authRequestDTO)) { + auditModules.add(AuditModules.PIN_AUTH); + } + + if (AuthTypeUtil.isBio(authRequestDTO)) { + if (authRequestDTO.getRequest() != null && authRequestDTO.getRequest().getBiometrics() != null) { + if ((authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData).anyMatch( + bioInfo -> BioAuthType.FGR_IMG.getType().equals(bioInfo.getBioType()) || (EnvUtil.getIsFmrEnabled() + && BioAuthType.FGR_MIN.getType().equals(bioInfo.getBioType()))))) { + auditModules.add(AuditModules.FINGERPRINT_AUTH); + } + + if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData) + .anyMatch(bioInfo -> BioAuthType.IRIS_IMG.getType().equals(bioInfo.getBioType()))) { + auditModules.add(AuditModules.IRIS_AUTH); + } + + if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData) + .anyMatch(bioInfo -> BioAuthType.FACE_IMG.getType().equals(bioInfo.getBioType()))) { + auditModules.add(AuditModules.FACE_AUTH); + } + } + } + + if (AuthTypeUtil.isKeyBindedToken(authRequestDTO)) { + auditModules.add(AuditModules.TOKEN_AUTH); + } + + if (AuthTypeUtil.isPassword(authRequestDTO)) { + auditModules.add(AuditModules.PASSWORD_AUTH); + } + return auditModules; + } + +} diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java index c7293860059..21fdcda6afa 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java @@ -535,6 +535,12 @@ private Map getEntityInfo(Map> idE IdAuthenticationErrorConstants.KEY_BINDING_MISSING.getErrorCode(), String.format(IdAuthenticationErrorConstants.KEY_BINDING_MISSING.getErrorMessage(), input.getAuthType().getType())); + + case PWD: + throw new IdAuthenticationBusinessException( + IdAuthenticationErrorConstants.PASSWORD_MISSING.getErrorCode(), + String.format(IdAuthenticationErrorConstants.PASSWORD_MISSING.getErrorMessage(), + input.getAuthType().getType())); } } return entityInfo; diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java index be8c0aa7aea..cdebdf68e2c 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java @@ -26,6 +26,7 @@ import io.mosip.authentication.common.service.impl.match.IdaIdMapping; import io.mosip.authentication.common.service.integration.MasterDataManager; import io.mosip.authentication.common.service.integration.OTPManager; +import io.mosip.authentication.common.service.integration.PasswordComparator; import io.mosip.authentication.common.service.util.BioMatcherUtil; import io.mosip.authentication.common.service.util.EnvUtil; import io.mosip.authentication.core.constant.IdAuthCommonConstants; @@ -37,6 +38,7 @@ import io.mosip.authentication.core.indauth.dto.RequestDTO; import io.mosip.authentication.core.spi.bioauth.CbeffDocType; import io.mosip.authentication.core.spi.indauth.match.AuthType; +import io.mosip.authentication.core.spi.indauth.match.ComparePasswordFunction; import io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher; import io.mosip.authentication.core.spi.indauth.match.IdMapping; import io.mosip.authentication.core.spi.indauth.match.MappingConfig; @@ -96,6 +98,9 @@ public class IdInfoFetcherImpl implements IdInfoFetcher { @Autowired(required = false) private KeyBindedTokenMatcherUtil keyBindedTokenMatcherUtil; + + @Autowired(required = false) + private PasswordComparator passwordComparator; /** * Gets the demo normalizer. @@ -572,4 +577,15 @@ public List getUserPreferredLanguages(Map> } return Collections.emptyList(); } + + /* + * Get Match password Function + * + * @see io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher# + * getMatchPasswordFunction() + */ + @Override + public ComparePasswordFunction getMatchPasswordFunction() { + return passwordComparator::matchPasswordFunction; + } } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java index fb5949bcd68..452a1c30d14 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java @@ -118,7 +118,7 @@ public Map getIdByVid(String vid, boolean isBio, Set fil public Map processIdType(String idvIdType, String idvId, boolean isBio, boolean markVidConsumed, Set filterAttributes) throws IdAuthenticationBusinessException { Map idResDTO = null; - if (idvIdType.equals(IdType.UIN.getType())) { + if (idvIdType.equals(IdType.UIN.getType()) || idvIdType.equals(IdType.HANDLE.getType())) { try { idResDTO = getIdByUin(idvId, isBio, filterAttributes); } catch (IdAuthenticationBusinessException e) { @@ -205,6 +205,9 @@ public Map getIdentity(String id, boolean isBio, IdType idType, idType.getType())); } + logger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "getIdentity", + "Generated HASHID >> " + hashedId); + if (isBio) { entity = identityRepo.getOne(hashedId); } else { @@ -254,6 +257,8 @@ public Map getIdentity(String id, boolean isBio, IdType idType, } responseMap.put(TOKEN, entity.getToken()); responseMap.put(ID_HASH, hashedId); + logger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "getIdentity", + "TOKEN in responseMap >> " + entity.getToken()); return responseMap; } catch (IOException | DataAccessException | TransactionException | JDBCConnectionException e) { logger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "getIdentity", diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/PasswordAuthServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/PasswordAuthServiceImpl.java new file mode 100644 index 00000000000..d337d55c482 --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/PasswordAuthServiceImpl.java @@ -0,0 +1,70 @@ +package io.mosip.authentication.common.service.impl; + +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import io.mosip.authentication.common.service.builder.AuthStatusInfoBuilder; +import io.mosip.authentication.common.service.builder.MatchInputBuilder; +import io.mosip.authentication.common.service.config.IDAMappingConfig; +import io.mosip.authentication.common.service.helper.IdInfoHelper; +import io.mosip.authentication.common.service.impl.match.PasswordAuthType; +import io.mosip.authentication.common.service.impl.match.PasswordMatchType; +import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; +import io.mosip.authentication.core.indauth.dto.AuthStatusInfo; +import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; +import io.mosip.authentication.core.spi.indauth.match.MatchInput; +import io.mosip.authentication.core.spi.indauth.match.MatchOutput; +import io.mosip.authentication.core.spi.indauth.service.PasswordAuthService; +import lombok.NoArgsConstructor; + +@Service +@NoArgsConstructor +public class PasswordAuthServiceImpl implements PasswordAuthService { + + @Autowired + private IdInfoHelper idInfoHelper; + + /** The id info helper. */ + @Autowired + private MatchInputBuilder matchInputBuilder; + + /** The ida mapping config. */ + @Autowired + private IDAMappingConfig idaMappingConfig; + + public AuthStatusInfo authenticate(AuthRequestDTO authRequestDTO,String individualId, + Map> idInfo,String partnerId) + throws IdAuthenticationBusinessException { + + if (idInfo == null || idInfo.isEmpty()) { + throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.SERVER_ERROR); + } + + List listMatchInputs = constructMatchInput(authRequestDTO, idInfo); + + List listMatchOutputs = constructMatchOutput(authRequestDTO, listMatchInputs, idInfo, + partnerId); + // Using AND condition on the match output for Bio auth. + boolean isMatched = !listMatchOutputs.isEmpty() && listMatchOutputs.stream().allMatch(MatchOutput::isMatched); + return AuthStatusInfoBuilder.buildStatusInfo(isMatched, listMatchInputs, listMatchOutputs, + PasswordAuthType.values(), idaMappingConfig); + + } + + public List constructMatchInput(AuthRequestDTO authRequestDTO, + Map> idInfo) { + return matchInputBuilder.buildMatchInput(authRequestDTO, PasswordAuthType.values(), PasswordMatchType.values(), + idInfo); + } + + private List constructMatchOutput(AuthRequestDTO authRequestDTO, List listMatchInputs, + Map> idInfo, String partnerId) + throws IdAuthenticationBusinessException { + return idInfoHelper.matchIdentityData(authRequestDTO, idInfo, listMatchInputs, partnerId); + } +} diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java index 789171e659b..4e3ccd80650 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java @@ -177,13 +177,14 @@ public String getSubType() { RIGHTIRIS, LEFTIRIS, UNKNOWN_IRIS, FACE,UNKNOWN_FACE), "DummyType"), - KEY_BINDED_TOKENS("keyBindedTokens"){ public BiFunction> getMappingFunction() { return (mappingConfig, matchType) -> { return Collections.emptyList(); }; } }, + PASSWORD("password", MappingConfig::getPassword), + /** The dynamic demographics ID Mapping. */ DYNAMIC("demographics") { diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordAuthType.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordAuthType.java new file mode 100644 index 00000000000..5c301684adf --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordAuthType.java @@ -0,0 +1,57 @@ +package io.mosip.authentication.common.service.impl.match; + +import io.mosip.authentication.common.service.impl.AuthTypeImpl; +import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; +import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO; +import io.mosip.authentication.core.spi.indauth.match.AuthType; +import io.mosip.authentication.core.spi.indauth.match.ComparePasswordFunction; +import io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher; +import io.mosip.authentication.core.spi.indauth.match.MatchType; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +public enum PasswordAuthType implements AuthType { + + PASSWORD(IdaIdMapping.PASSWORD.getIdname(), AuthType.setOf(PasswordMatchType.PASSWORD), "PASSWORD"); + + private AuthTypeImpl authTypeImpl; + + /** + * Instantiates a new demo auth type. + * + * @param type the type + * @param associatedMatchTypes the associated match types + */ + private PasswordAuthType(String type, Set associatedMatchTypes, String displayName) { + authTypeImpl = new AuthTypeImpl(type, associatedMatchTypes, displayName); + } + + + @Override + public boolean isAuthTypeInfoAvailable(AuthRequestDTO authRequestDTO) { + if(authRequestDTO instanceof KycAuthRequestDTO) { + KycAuthRequestDTO kycAuthRequestDTO = (KycAuthRequestDTO) authRequestDTO; + return Objects.nonNull(kycAuthRequestDTO.getRequest().getPassword()); + } + return false; + } + + @Override + public Map getMatchProperties(AuthRequestDTO authRequestDTO, IdInfoFetcher idInfoFetcher, + String language) { + Map valueMap = new HashMap<>(); + if(isAuthTypeInfoAvailable(authRequestDTO)) { + ComparePasswordFunction func = idInfoFetcher.getMatchPasswordFunction(); + valueMap.put(IdaIdMapping.PASSWORD.getIdname(), func); + } + return valueMap; + } + + @Override + public AuthType getAuthTypeImpl() { + return authTypeImpl; + } +} diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchType.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchType.java new file mode 100644 index 00000000000..6eee7370204 --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchType.java @@ -0,0 +1,131 @@ +package io.mosip.authentication.common.service.impl.match; + +import static io.mosip.authentication.core.spi.indauth.match.MatchType.setOf; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; + +import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; +import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; +import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO; +import io.mosip.authentication.core.indauth.dto.RequestDTO; +import io.mosip.authentication.core.spi.indauth.match.IdMapping; +import io.mosip.authentication.core.spi.indauth.match.MatchType; +import io.mosip.authentication.core.spi.indauth.match.MatchingStrategy; +import io.mosip.authentication.core.spi.indauth.match.MatchingStrategyType; + +public enum PasswordMatchType implements MatchType { + + /** Primary password Match Type. */ + PASSWORD(IdaIdMapping.PASSWORD, Category.PWD, setOf(PasswordMatchingStrategy.EXACT), authReq -> { + KycAuthRequestDTO kycAuthRequestDTO = (KycAuthRequestDTO)authReq; + return (Objects.nonNull(kycAuthRequestDTO.getRequest()) && + Objects.nonNull(kycAuthRequestDTO.getRequest().getPassword()))? kycAuthRequestDTO.getRequest().getPassword() : ""; + }); + + /** The allowed matching strategy. */ + private Set allowedMatchingStrategy; + + /** The request info function. */ + private Function> requestInfoFunction; + + /** The id mapping. */ + private IdMapping idMapping; + + private Category category; + + /** + * Instantiates a new demo match type. + * + * @param idMapping the id mapping + * @param allowedMatchingStrategy the allowed matching strategy + * @param requestInfoFunction the request info function + * @param langType the lang type + * @param usedBit the used bit + * @param matchedBit the matched bit + */ + private PasswordMatchType(IdMapping idMapping, Category category, Set allowedMatchingStrategy, + Function requestInfoFunction) { + this.idMapping = idMapping; + this.category = category; + this.requestInfoFunction = (AuthRequestDTO authReq) -> { + Map map = new HashMap<>(); + map.put(idMapping.getIdname(), requestInfoFunction.apply(authReq)); + return map; + }; + this.allowedMatchingStrategy = Collections.unmodifiableSet(allowedMatchingStrategy); + } + + /** + * Gets the allowed matching strategy. + * + * @param matchStrategyType the match strategy type + * @return the allowed matching strategy + */ + public Optional getAllowedMatchingStrategy(MatchingStrategyType matchStrategyType) { + return allowedMatchingStrategy.stream().filter(ms -> ms.getType().equals(matchStrategyType)).findAny(); + } + + /** + * Gets the entity info. + * + * @return the entity info + */ + public BiFunction, Map, Map> getEntityInfoMapper() { + return (entity, props) -> entity; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.authentication.service.impl.indauth.service.demo.MatchType# + * getIdMapping() + */ + public IdMapping getIdMapping() { + return idMapping; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.authentication.service.impl.indauth.service.demo.MatchType# + * getIdentityInfoFunction() + */ + @Override + public Function>> getIdentityInfoFunction() { + return id -> Collections.emptyMap(); + } + + /* + * (non-Javadoc) + * + * @see io.mosip.authentication.core.spi.indauth.match.MatchType#getCategory() + */ + @Override + public Category getCategory() { + return category; + } + + @Override + public Function> getReqestInfoFunction() { + return requestInfoFunction; + } + + @Override + public boolean hasIdEntityInfo() { + return true; + } + + @Override + public boolean hasRequestEntityInfo() { + return false; + } + +} diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchingStrategy.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchingStrategy.java new file mode 100644 index 00000000000..a567dedf1fe --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchingStrategy.java @@ -0,0 +1,92 @@ +package io.mosip.authentication.common.service.impl.match; + +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.SEMI_COLON; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.COLON; + +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +import io.mosip.authentication.core.constant.IdAuthCommonConstants; +import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.logger.IdaLogger; +import io.mosip.authentication.core.spi.indauth.match.ComparePasswordFunction; +import io.mosip.authentication.core.spi.indauth.match.MatchFunction; +import io.mosip.authentication.core.spi.indauth.match.MatchingStrategy; +import io.mosip.authentication.core.spi.indauth.match.MatchingStrategyType; +import io.mosip.authentication.core.util.DemoMatcherUtil; +import io.mosip.kernel.core.logger.spi.Logger; + +public enum PasswordMatchingStrategy implements MatchingStrategy { + + EXACT(MatchingStrategyType.EXACT, (Object reqInfo, Object entityInfo, Map props) -> { + if (reqInfo instanceof Map && entityInfo instanceof Map) { + Object object = props.get(IdaIdMapping.PASSWORD.getIdname()); + if (object instanceof ComparePasswordFunction) { + ComparePasswordFunction func = (ComparePasswordFunction) object; + Map entityInfoMap = (Map) entityInfo; + Map reqInfoMap = (Map) reqInfo; + String hashSaltValue = entityInfoMap.get(IdaIdMapping.PASSWORD.getIdname()); + Map passwordMap = Arrays.stream(hashSaltValue.split(SEMI_COLON)) + .map(str -> str.split(String.valueOf(COLON), 2)) + .collect(Collectors.toMap(strArr -> strArr[0].trim(), strArr -> strArr[1].trim())); + + String passwordHashedValue = passwordMap.get(IdAuthCommonConstants.HASH); + String salt = passwordMap.get(IdAuthCommonConstants.SALT); + String reqInfoValue = reqInfoMap.get(IdaIdMapping.PASSWORD.getIdname()); + boolean matched = func.matchPasswordFunction(reqInfoValue, passwordHashedValue, salt); + return !matched ? 0 : 100; + } else { + logError(); + throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.PASSWORD_MISMATCH.getErrorCode(), + IdAuthenticationErrorConstants.PASSWORD_MISMATCH.getErrorMessage()); + } + } + return 0; + }); + + private final MatchFunction matchFunction; + + /** The match strategy type. */ + private final MatchingStrategyType matchStrategyType; + + private static Logger mosipLogger = IdaLogger.getLogger(PasswordMatchingStrategy.class); + + /** + * Instantiates a new Token matching strategy. + * + * @param matchStrategyType the match strategy type + * @param matchFunction the match function + */ + private PasswordMatchingStrategy(MatchingStrategyType matchStrategyType, MatchFunction matchFunction) { + this.matchFunction = matchFunction; + this.matchStrategyType = matchStrategyType; + } + + /* (non-Javadoc) + * @see io.mosip.authentication.core.spi.indauth.match.MatchingStrategy#getType() + */ + @Override + public MatchingStrategyType getType() { + return matchStrategyType; + } + + /* (non-Javadoc) + * @see io.mosip.authentication.core.spi.indauth.match.MatchingStrategy#getMatchFunction() + */ + @Override + public MatchFunction getMatchFunction() { + return matchFunction; + } + + private static void logError() { + mosipLogger.error(IdAuthCommonConstants.SESSION_ID, IdAuthCommonConstants.PASSWORD_BASED_AUTH, + "Error in Passward Matching Strategy"); + } + + public static DemoMatcherUtil getDemoMatcherUtilObject(Map props) { + return (DemoMatcherUtil)props.get("demoMatcherUtil"); + } + +} diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PartnerServiceManager.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PartnerServiceManager.java index a08ca20be83..10f08d184b0 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PartnerServiceManager.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PartnerServiceManager.java @@ -209,8 +209,8 @@ private void validatePartnerMappingDetails(Optional partnerMappi if (partnerMapping.getApiKeyData().getApiKeyCommenceOn().isAfter(DateUtils.getUTCCurrentDateTime()) || partnerMapping.getApiKeyData().getApiKeyExpiresOn() .isBefore(DateUtils.getUTCCurrentDateTime())) { - throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.PARTNER_NOT_REGISTERED.getErrorCode(), - IdAuthenticationErrorConstants.PARTNER_NOT_REGISTERED.getErrorMessage()); + throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.PARTNER_API_EXPIRED.getErrorCode(), + IdAuthenticationErrorConstants.PARTNER_API_EXPIRED.getErrorMessage()); } } else { logger.info(IdAuthCommonConstants.IDA, this.getClass().getSimpleName(), "OIDC_client_validation", diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PasswordComparator.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PasswordComparator.java new file mode 100644 index 00000000000..cafaa686935 --- /dev/null +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/integration/PasswordComparator.java @@ -0,0 +1,39 @@ + package io.mosip.authentication.common.service.integration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; +import io.mosip.authentication.core.constant.IdAuthCommonConstants; +import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.logger.IdaLogger; +import io.mosip.kernel.core.logger.spi.Logger; + + +/** + * This Class will compare the input password value with the stored Hash value & salt + * + */ +@Component +public class PasswordComparator { + + @Autowired(required = false) + private IdAuthSecurityManager securityManager; + + /** + * Logger + */ + private static Logger logger = IdaLogger.getLogger(PasswordComparator.class); + + public boolean matchPasswordFunction(String passwordValue, String passwordHashValue, String salt) throws IdAuthenticationBusinessException { + + try { + String inputPasswordHash = securityManager.generateArgon2Hash(passwordValue, salt); + return inputPasswordHash.equals(passwordHashValue); + } catch (Exception e) { + logger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(), e.getLocalizedMessage(),e.getMessage()); + throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.SERVER_ERROR, e); + } + } +} diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/MispLicenseDataRepository.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/MispLicenseDataRepository.java index e2fc5039bbe..3ce5c9844f7 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/MispLicenseDataRepository.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/MispLicenseDataRepository.java @@ -1,13 +1,20 @@ package io.mosip.authentication.common.service.repository; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.MISP_LIC_DATA; + import java.util.Optional; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import io.mosip.authentication.common.service.entity.MispLicenseData; public interface MispLicenseDataRepository extends JpaRepository { - Optional findByLicenseKey(String licenseKey); + @Cacheable(value = MISP_LIC_DATA, unless ="#result == null") + @Query("select ml from MispLicenseData ml where ml.licenseKey = :licenseKey") + Optional findByLicenseKey(@Param("licenseKey") String licenseKey); } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/OIDCClientDataRepository.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/OIDCClientDataRepository.java index 22e2fc14412..8bb3e9bbe42 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/OIDCClientDataRepository.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/OIDCClientDataRepository.java @@ -1,8 +1,13 @@ package io.mosip.authentication.common.service.repository; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.OIDC_CLIENT_DATA; + import java.util.Optional; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import io.mosip.authentication.common.service.entity.OIDCClientData; @@ -16,5 +21,7 @@ @Repository public interface OIDCClientDataRepository extends JpaRepository { - Optional findByClientId(String clientId); + @Cacheable(value = OIDC_CLIENT_DATA, unless ="#result == null") + @Query("select oi from OIDCClientData oi where oi.clientId = :clientId") + Optional findByClientId(@Param("clientId") String clientId); } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerDataRepository.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerDataRepository.java index 968ebfc97da..6823f120100 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerDataRepository.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerDataRepository.java @@ -1,12 +1,19 @@ package io.mosip.authentication.common.service.repository; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.PARTNER_DATA; + import java.util.Optional; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import io.mosip.authentication.common.service.entity.PartnerData; public interface PartnerDataRepository extends JpaRepository { - Optional findByPartnerId(String partnerId); + @Cacheable(value = PARTNER_DATA, unless ="#result == null") + @Query("select pd from PartnerData pd where pd.partnerId = :partnerId") + Optional findByPartnerId(@Param("partnerId") String partnerId); } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerMappingRepository.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerMappingRepository.java index 0484d26bf67..9a7afa81119 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerMappingRepository.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PartnerMappingRepository.java @@ -1,16 +1,25 @@ package io.mosip.authentication.common.service.repository; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.PARTNER_API_KEY_DATA; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.PARTNER_API_KEY_POLICY_ID_DATA; + import java.util.Optional; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import io.mosip.authentication.common.service.entity.PartnerMapping; public interface PartnerMappingRepository extends JpaRepository { - Optional findByPartnerIdAndApiKeyId(String partnerId, String apiKeyId); - - Optional findByPartnerId(String partnerId); + @Cacheable(value = PARTNER_API_KEY_DATA, unless ="#result == null") + @Query("select pm from PartnerMapping pm where pm.partnerId = :partnerId and pm.apiKeyId = :apiKeyId") + Optional findByPartnerIdAndApiKeyId(@Param("partnerId") String partnerId, @Param("apiKeyId") String apiKeyId); - Optional findByPartnerIdAndApiKeyIdAndPolicyId(String partnerId, String apiKeyId, String policyId); + @Cacheable(value = PARTNER_API_KEY_POLICY_ID_DATA, unless ="#result == null") + @Query("select pm from PartnerMapping pm where pm.partnerId = :partnerId and pm.apiKeyId = :apiKeyId and pm.policyId = :policyId") + Optional findByPartnerIdAndApiKeyIdAndPolicyId(@Param("partnerId") String partnerId, @Param("apiKeyId") String apiKeyId, + @Param("policyId") String policyId); } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PolicyDataRepository.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PolicyDataRepository.java index 06dbdeac426..fd883390f4d 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PolicyDataRepository.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/repository/PolicyDataRepository.java @@ -1,13 +1,20 @@ package io.mosip.authentication.common.service.repository; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.POLICY_DATA; + import java.util.Optional; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import io.mosip.authentication.common.service.entity.PolicyData; public interface PolicyDataRepository extends JpaRepository { - Optional findByPolicyId(String policyId); + @Cacheable(value = POLICY_DATA, unless ="#result == null") + @Query("select pd from PolicyData pd where pd.policyId = :policyId") + Optional findByPolicyId(@Param("policyId") String policyId); } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/transaction/manager/IdAuthSecurityManager.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/transaction/manager/IdAuthSecurityManager.java index 6115f62ef9c..412ec9aefe0 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/transaction/manager/IdAuthSecurityManager.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/transaction/manager/IdAuthSecurityManager.java @@ -49,6 +49,8 @@ import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.core.util.HMACUtils2; import io.mosip.kernel.crypto.jce.core.CryptoCore; +import io.mosip.kernel.cryptomanager.dto.Argon2GenerateHashRequestDto; +import io.mosip.kernel.cryptomanager.dto.Argon2GenerateHashResponseDto; import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; import io.mosip.kernel.cryptomanager.dto.JWTCipherResponseDto; import io.mosip.kernel.cryptomanager.service.CryptomanagerService; @@ -705,4 +707,12 @@ public String jwtEncrypt(String dataToEncrypt, String certificateData) { JWTCipherResponseDto cipherResponseDto = cryptomanagerService.jwtEncrypt(encryptRequestDto); return cipherResponseDto.getData(); } + + public String generateArgon2Hash(String anyString, String salt) { + Argon2GenerateHashRequestDto hashRequestDto = new Argon2GenerateHashRequestDto(); + hashRequestDto.setInputData(anyString); + hashRequestDto.setSalt(salt); + Argon2GenerateHashResponseDto hashResponseDto = cryptomanagerService.generateArgon2Hash(hashRequestDto); + return hashResponseDto.getHashValue(); + } } diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/util/AuthTypeUtil.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/util/AuthTypeUtil.java index 4847e1e3d05..5c6ea119e84 100644 --- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/util/AuthTypeUtil.java +++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/util/AuthTypeUtil.java @@ -9,6 +9,7 @@ import io.mosip.authentication.common.service.impl.match.DemoAuthType; import io.mosip.authentication.common.service.impl.match.PinAuthType; import io.mosip.authentication.common.service.impl.match.KeyBindedTokenAuthType; +import io.mosip.authentication.common.service.impl.match.PasswordAuthType; import io.mosip.authentication.core.constant.RequestType; import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; import io.mosip.authentication.core.indauth.dto.EkycAuthRequestDTO; @@ -38,6 +39,10 @@ public static boolean isKeyBindedToken(AuthRequestDTO authReqDto) { return isAuthTypeInfoAvailable(authReqDto, new AuthType[] {KeyBindedTokenAuthType.KEYBINDEDTOKEN}); } + public static boolean isPassword(AuthRequestDTO authReqDto) { + return isAuthTypeInfoAvailable(authReqDto, new AuthType[] {PasswordAuthType.PASSWORD}); + } + private static boolean isAuthTypeInfoAvailable(AuthRequestDTO authReqDto, AuthType[] values) { return Stream.of(values).anyMatch(authType -> authType.isAuthTypeInfoAvailable(authReqDto)); } @@ -67,6 +72,10 @@ public static List findAutRequestTypes(AuthRequestDTO authRequestDT if(authRequestDTO instanceof EkycAuthRequestDTO) { requestTypes.add(RequestType.EKYC_AUTH_REQUEST); } + + if (AuthTypeUtil.isPassword(authRequestDTO)) { + requestTypes.add(RequestType.PASSWORD_AUTH); + } return requestTypes; } diff --git a/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/helper/TokenValidationHelperTest.java b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/helper/TokenValidationHelperTest.java new file mode 100644 index 00000000000..0e7b328781a --- /dev/null +++ b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/helper/TokenValidationHelperTest.java @@ -0,0 +1,139 @@ +package io.mosip.authentication.common.service.helper; + +import io.mosip.authentication.common.service.entity.KycTokenData; +import io.mosip.authentication.common.service.repository.KycTokenDataRepository; +import io.mosip.authentication.common.service.repository.OIDCClientDataRepository; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.spi.indauth.service.KycService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.test.context.junit4.SpringRunner; + +import java.time.LocalDateTime; +import java.util.*; + +@RunWith(SpringRunner.class) +public class TokenValidationHelperTest { + + /** The Kyc Service */ + @Mock + private KycService kycService; + + @Mock + private KycTokenDataRepository kycTokenDataRepo; + + @Mock + private IdInfoHelper idInfoHelper; + + @Mock + private OIDCClientDataRepository oidcClientDataRepo; + + @InjectMocks + TokenValidationHelper tokenValidationHelper; + + + @Test + public void findAndValidateIssuedTokenTestWithValidDetails_thenPass() throws IdAuthenticationBusinessException { + + KycTokenData kycTokenData = new KycTokenData(); + kycTokenData.setPsuToken("1234567890"); + kycTokenData.setKycToken("1234567890"); + kycTokenData.setKycTokenStatus("ACTIVE"); + kycTokenData.setOidcClientId("12345"); + kycTokenData.setTokenIssuedDateTime(LocalDateTime.now()); + kycTokenData.setIdVidHash("1234567"); + kycTokenData.setRequestTransactionId("123456"); + Mockito.when(kycTokenDataRepo.findByKycToken(Mockito.anyString())).thenReturn(Optional.of(kycTokenData)); + Mockito.when( kycService.isKycTokenExpire(Mockito.any(),Mockito.anyString())).thenReturn(false); + + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12345", "123456", "1234567"); + + } + + @Test + public void findAndValidateIssuedTokenTestWithInValidTokenDetails_thenFail() throws IdAuthenticationBusinessException { + + Mockito.when(kycTokenDataRepo.findByKycToken(Mockito.anyString())).thenReturn(Optional.empty()); + Mockito.when( kycService.isKycTokenExpire(Mockito.any(),Mockito.anyString())).thenReturn(false); + + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12346", "123456", "1234567"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-001")); + } + + } + + @Test + public void findAndValidateIssuedTokenTestWithExpiredTokenDetails_thenFail() throws IdAuthenticationBusinessException { + + KycTokenData kycTokenData = new KycTokenData(); + kycTokenData.setPsuToken("1234567890"); + kycTokenData.setKycToken("1234567890"); + kycTokenData.setKycTokenStatus("ACTIVE"); + kycTokenData.setOidcClientId("12345"); + kycTokenData.setTokenIssuedDateTime(LocalDateTime.now()); + kycTokenData.setIdVidHash("1234567"); + kycTokenData.setRequestTransactionId("123456"); + Mockito.when(kycTokenDataRepo.findByKycToken(Mockito.anyString())).thenReturn(Optional.of(kycTokenData)); + Mockito.when( kycService.isKycTokenExpire(Mockito.any(),Mockito.anyString())).thenReturn(true); + + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12345", "123456", "1234567"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-002")); + } + + } + + @Test + public void findAndValidateIssuedTokenTestWithInValidDetails_thenPass() throws IdAuthenticationBusinessException { + + KycTokenData kycTokenData = new KycTokenData(); + kycTokenData.setPsuToken("1234567890"); + kycTokenData.setKycToken("1234567890"); + kycTokenData.setKycTokenStatus("ACTIVE"); + kycTokenData.setOidcClientId("12345"); + kycTokenData.setTokenIssuedDateTime(LocalDateTime.now()); + kycTokenData.setIdVidHash("1234567"); + kycTokenData.setRequestTransactionId("123456"); + Mockito.when(kycTokenDataRepo.findByKycToken(Mockito.anyString())).thenReturn(Optional.of(kycTokenData)); + Mockito.when( kycService.isKycTokenExpire(Mockito.any(),Mockito.anyString())).thenReturn(false); + + + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12346", "123456", "1234567"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-004")); + } + + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12345", "123457", "1234567"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-005")); + } + + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12345", "123456", "1234568"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-007")); + } + + kycTokenData.setKycTokenStatus("EXPIRED"); + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12345", "123456", "1234567"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-002")); + } + + kycTokenData.setKycTokenStatus("PROCESSED"); + try{ + tokenValidationHelper.findAndValidateIssuedToken("1234567890", "12345", "123456", "1234567"); + }catch (IdAuthenticationBusinessException e){ + assert(e.getErrorCode().equalsIgnoreCase("IDA-KYE-003")); + } + } +} diff --git a/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/impl/KeyBindedTokenAuthServiceImplTest.java b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/impl/KeyBindedTokenAuthServiceImplTest.java new file mode 100644 index 00000000000..3ca7339c265 --- /dev/null +++ b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/impl/KeyBindedTokenAuthServiceImplTest.java @@ -0,0 +1,69 @@ +package io.mosip.authentication.common.service.impl; + + +import io.mosip.authentication.common.service.builder.MatchInputBuilder; +import io.mosip.authentication.common.service.config.IDAMappingConfig; +import io.mosip.authentication.common.service.helper.IdInfoHelper; +import io.mosip.authentication.common.service.repository.IdentityBindingCertificateRepository; +import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.indauth.dto.AuthRequestDTO; +import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; +import io.mosip.authentication.core.spi.indauth.match.MatchOutput; +import org.apache.commons.collections.map.HashedMap; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +public class KeyBindedTokenAuthServiceImplTest { + + @InjectMocks + IdInfoHelper idInfoHelper; + + /** The id info helper. */ + @Mock + MatchInputBuilder matchInputBuilder; + + /** The ida mapping config. */ + @Mock + IDAMappingConfig idaMappingConfig; + + @Mock + IdAuthSecurityManager securityManager; + + @Mock + IdentityBindingCertificateRepository identityBindingCertificateRepository; + + @InjectMocks + KeyBindedTokenAuthServiceImpl keyBindedTokenAuthService; + + @Test + public void authenticateTestWithValidDetails_thenPass() throws IdAuthenticationBusinessException { + AuthRequestDTO authRequestDTO = new AuthRequestDTO(); + + ReflectionTestUtils.setField(keyBindedTokenAuthService,"idInfoHelper",idInfoHelper); + IdentityInfoDTO identityInfoDTO=new IdentityInfoDTO(); + identityInfoDTO.setValue("value"); + identityInfoDTO.setLanguage("end"); + List list=new ArrayList<>(); + list.add(identityInfoDTO); + Map> idInfo= new HashedMap(); + idInfo.put("key",list); + + MatchOutput matchOutput=new MatchOutput(5,true,"fingerpring",null,"end","idName"); + + matchOutput.setLanguage("end"); + List matchOutputList=new ArrayList<>(); + matchOutputList.add(matchOutput); + keyBindedTokenAuthService.authenticate(authRequestDTO,"individualId",idInfo,"partnerId"); + + } +} diff --git a/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/integration/PartnerServiceManagerTest.java b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/integration/PartnerServiceManagerTest.java index 1bf210f2b49..f8acdee39fd 100644 --- a/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/integration/PartnerServiceManagerTest.java +++ b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/integration/PartnerServiceManagerTest.java @@ -865,7 +865,7 @@ public void Test_validatePartnerMappingDetails_apikeyCommenceNotBefore() { if (e.getUndeclaredThrowable() instanceof IdAuthenticationBaseException) { IdAuthenticationBaseException idAuthenticationBaseException = (IdAuthenticationBaseException) e .getUndeclaredThrowable(); - assertEquals(IdAuthenticationErrorConstants.PARTNER_NOT_REGISTERED.getErrorCode(), + assertEquals(IdAuthenticationErrorConstants.PARTNER_API_EXPIRED.getErrorCode(), idAuthenticationBaseException.getErrorCode()); } } @@ -898,7 +898,7 @@ public void Test_validatePartnerMappingDetails_apikeyExpiryNotAfter() { if (e.getUndeclaredThrowable() instanceof IdAuthenticationBaseException) { IdAuthenticationBaseException idAuthenticationBaseException = (IdAuthenticationBaseException) e .getUndeclaredThrowable(); - assertEquals(IdAuthenticationErrorConstants.PARTNER_NOT_REGISTERED.getErrorCode(), + assertEquals(IdAuthenticationErrorConstants.PARTNER_API_EXPIRED.getErrorCode(), idAuthenticationBaseException.getErrorCode()); } } diff --git a/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/util/KeyBindedTokenMatcherUtilTest.java b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/util/KeyBindedTokenMatcherUtilTest.java new file mode 100644 index 00000000000..6bfd363de7d --- /dev/null +++ b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/util/KeyBindedTokenMatcherUtilTest.java @@ -0,0 +1,157 @@ +package io.mosip.authentication.common.service.util; + +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; +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.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +@RunWith(SpringRunner.class) +public class KeyBindedTokenMatcherUtilTest { + + @Mock + KeymanagerUtil keymanagerUtil; + @InjectMocks + KeyBindedTokenMatcherUtil keyBindedTokenMatcherUtil; + + + @Test + public void matchTestWithInValidToken_thenFail() { + + Map properties =new HashMap<>(); + Map bindingCertificates =new HashMap<>(); + Map input =new HashMap<>(); + input.put("individualId","individualId"); + input.put("type","type"); + input.put("format","jwt"); + input.put("token",".eyJ"); + + try{ + keyBindedTokenMatcherUtil.match(input, bindingCertificates, properties); + }catch (IdAuthenticationBusinessException e){ + } + } + @Test + public void matchTestWithExpiredToken_thenFail() { + + Map properties =new HashMap<>(); + Map bindingCertificates =new HashMap<>(); + Map input =new HashMap<>(); + input.put("individualId","individualId"); + input.put("type","type"); + input.put("format","jwt"); + input.put("token","eyJ0eXAiOiJKV1QiLCJ4NXQjUzI1NiI6IjBFSmtKMDYyWnZNZ0dKSk9BRVNYWFo1Tl9hamRDOG04Y0hPTXVKVVRGWUEiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2OTg5ODgyMTcsIm5iZiI6MTY5ODk4ODIxNywiZXhwIjoxNjk4OTg4ODIyLCJqdGkiOiJYZkpRaGVfU3RuNTNmaWc3YVV3V3MiLCJhdWQiOiJpZGEtYmluZGluZyIsInN1YiI6IjQxNTg2MTI2MDkiLCJpc3MiOiJwb3N0bWFuLWluamkifQ.bSqcJZlq5PyAExwPoww41OF-vBIyaADZ8OsXzA_7gtowNl0kChVAB11eIPEcjuFvYeQiSpQgNZsS2-w84ZBdiqh72kkJQLjN7ItMKNf-cekNRmG6XFf1os1vom7CwrguataoYvboiiXYw0WUfsZTmnhcOKC8XN3qAsB2YAyYEnBJBeKy5aCNAfJiOULTMrqAqcu-A1MA_wtAkaCJggiNxf1-5bJWjZYyQOkis0nHmbgWjzzThdd6TzMkLnUyNxzO2n1E9A19OJ2ZH0ZN1d46c8QBMsYmGX-Kz8B8GBDnDlwC4M5g4hmxuXCN6sBcVjAONl92LxI1htSZ6muv3xL1YQ"); + + try{ + keyBindedTokenMatcherUtil.match(input, bindingCertificates, properties); + }catch (IdAuthenticationBusinessException e){ + Assert.assertEquals("IDA-KBT-002",e.getErrorCode()); + } + } + + @Test + public void matchTestWithInValidThumbprint_thenFail() { + + Map properties =new HashMap<>(); + Map bindingCertificates =new HashMap<>(); + Map input =new HashMap<>(); + input.put("individualId","individualId"); + input.put("type","type"); + input.put("format","jwt"); + input.put("token","eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJrdHkiOiJSU0EiLCJlIjoiQVFBQiIsInVzZSI6InNpZyIsImtpZCI6IkFBNzBWbUQ2OGltaUU2NDhSdDBzRWNhc1N3VkJDNGxtbno4ZUFPZmRYQzgiLCJhbGciOiJSUzI1NiIsIm4iOiJzZFNtY0o1bzJZX1JMOURORXFEQl9fV0xqV1RUY3JvRHpMaXRFRUxSb3h3MF9talV1azAyd1NlcTY3YlR4YzR0b2JMTS04Y19DNkVsNUgtQzlsTFF3VURZYnZ1VmxpX2lBLWtvZ0Rxa1dOTEEwbWZaLW9FRUtEYTlJV280VmY4MHl2Z09EN2hfSlpCWG53dHZjaTRqUlNaekc1R05sU2VJY25ZU0tiNVpvTTBOVDEtb0VrLU1tQnIxcmZGYWpGZ0hvMXhQSTQwUkN6UFhNWnkwOXY5Y2R5SVdTbWFzd2VRMmcxbEtsVHhqcVhibEtiTjZMQzNhUXc2azlFVVEzNjJ5QW5FMmZWOWpkcmNFb29RT0ZYZk1ZTHQ2UlFRMmJQSjIxb01aT0RGUjU0cHlVT0RxdlowMnczcnZMS0ozU2dvTHEtLVlDUTEzNi04cWJqNXpTVnNwMlEiLCJpYXQiOjE2OTg5OTQzMzR9.J4DNzGDNWE6AIIg7PAF8CZufFOOKA97ngBn1xMU05T9X_eqV9mfSk3G-fDXRRGS3ucS25gB2k6kOh7vt0eoVYEgw1lOQ2ERM2UoT7sWzUYvt0zedkP2zgkcubkeOwC-dY65_NiFRZ4iXudu38iLd2iQcAdwnp9e5HBfCFxiVkxIByMfGac6SwrCByNnPQnaiYn_988UKW7YVoqK4NK2kIJ405bz9kRWb8MMIRSTRskg0gYoQs9tCQGfD0QJWjJGk_Qqj2eDuH2pHresKELchjhe9hbbkajG021azpvPdq3t4PrYlqhiFajE-MRKwAR7Ey3_CfSHSoJ4mg2OBrhOVsA"); + + try{ + keyBindedTokenMatcherUtil.match(input, bindingCertificates, properties); + }catch (IdAuthenticationBusinessException e){ + Assert.assertEquals("IDA-MLC-009",e.getErrorCode()); + } + } + @Test + public void matchTestWithInValidCerts_thenFail() throws IdAuthenticationBusinessException { + ReflectionTestUtils.setField(keyBindedTokenMatcherUtil, "iatAdjSeconds", 30000000); + Map properties =new HashMap<>(); + Map bindingCertificates =new HashMap<>(); + Map input =new HashMap<>(); + input.put("individualId","individualId"); + input.put("type","type"); + input.put("format","jwt"); + input.put("token","eyJ0eXAiOiJKV1QiLCJ4NXQjUzI1NiI6IjBFSmtKMDYyWnZNZ0dKSk9BRVNYWFo1Tl9hamRDOG04Y0hPTXVKVVRGWUEiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2OTg5ODgyMTcsIm5iZiI6MTY5ODk4ODIxNywiZXhwIjoxNjk4OTg4ODIyLCJqdGkiOiJYZkpRaGVfU3RuNTNmaWc3YVV3V3MiLCJhdWQiOiJpZGEtYmluZGluZyIsInN1YiI6IjQxNTg2MTI2MDkiLCJpc3MiOiJwb3N0bWFuLWluamkifQ.bSqcJZlq5PyAExwPoww41OF-vBIyaADZ8OsXzA_7gtowNl0kChVAB11eIPEcjuFvYeQiSpQgNZsS2-w84ZBdiqh72kkJQLjN7ItMKNf-cekNRmG6XFf1os1vom7CwrguataoYvboiiXYw0WUfsZTmnhcOKC8XN3qAsB2YAyYEnBJBeKy5aCNAfJiOULTMrqAqcu-A1MA_wtAkaCJggiNxf1-5bJWjZYyQOkis0nHmbgWjzzThdd6TzMkLnUyNxzO2n1E9A19OJ2ZH0ZN1d46c8QBMsYmGX-Kz8B8GBDnDlwC4M5g4hmxuXCN6sBcVjAONl92LxI1htSZ6muv3xL1YQ"); + + try { + keyBindedTokenMatcherUtil.match(input, bindingCertificates, properties); + }catch (IdAuthenticationBusinessException e){ + Assert.assertEquals("IDA-KBT-001",e.getErrorCode()); + } + } + + @Test + public void matchTestWithValidCerts_thenFail() throws IdAuthenticationBusinessException { + ReflectionTestUtils.setField(keyBindedTokenMatcherUtil, "iatAdjSeconds", 300000000); + Map properties =new HashMap<>(); + Map bindingCertificates =new HashMap<>(); + bindingCertificates.put("D04264274EB666F32018924E0044975D9E4DFDA8DD0BC9BC70738CB895131580-TYPE","X509"); + Map input =new HashMap<>(); + input.put("individualId","individualId"); + input.put("type","type"); + input.put("format","jwt"); + input.put("token","eyJ0eXAiOiJKV1QiLCJ4NXQjUzI1NiI6IjBFSmtKMDYyWnZNZ0dKSk9BRVNYWFo1Tl9hamRDOG04Y0hPTXVKVVRGWUEiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2OTg5ODgyMTcsIm5iZiI6MTY5ODk4ODIxNywiZXhwIjoxNjk4OTg4ODIyLCJqdGkiOiJYZkpRaGVfU3RuNTNmaWc3YVV3V3MiLCJhdWQiOiJpZGEtYmluZGluZyIsInN1YiI6IjQxNTg2MTI2MDkiLCJpc3MiOiJwb3N0bWFuLWluamkifQ.bSqcJZlq5PyAExwPoww41OF-vBIyaADZ8OsXzA_7gtowNl0kChVAB11eIPEcjuFvYeQiSpQgNZsS2-w84ZBdiqh72kkJQLjN7ItMKNf-cekNRmG6XFf1os1vom7CwrguataoYvboiiXYw0WUfsZTmnhcOKC8XN3qAsB2YAyYEnBJBeKy5aCNAfJiOULTMrqAqcu-A1MA_wtAkaCJggiNxf1-5bJWjZYyQOkis0nHmbgWjzzThdd6TzMkLnUyNxzO2n1E9A19OJ2ZH0ZN1d46c8QBMsYmGX-Kz8B8GBDnDlwC4M5g4hmxuXCN6sBcVjAONl92LxI1htSZ6muv3xL1YQ"); + String certificateString="-----BEGIN CERTIFICATE-----\n" + + "MIIC6jCCAdKgAwIBAgIGAYuT8Am8MA0GCSqGSIb3DQEBCwUAMDYxNDAyBgNVBAMM\n" + + "K0FBNzBWbUQ2OGltaUU2NDhSdDBzRWNhc1N3VkJDNGxtbno4ZUFPZmRYQzgwHhcN\n" + + "MjMxMTAzMDY0NzQzWhcNMjQwODI5MDY0NzQzWjA2MTQwMgYDVQQDDCtBQTcwVm1E\n" + + "NjhpbWlFNjQ4UnQwc0VjYXNTd1ZCQzRsbW56OGVBT2ZkWEM4MIIBIjANBgkqhkiG\n" + + "9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsdSmcJ5o2Y/RL9DNEqDB//WLjWTTcroDzLit\n" + + "EELRoxw0/mjUuk02wSeq67bTxc4tobLM+8c/C6El5H+C9lLQwUDYbvuVli/iA+ko\n" + + "gDqkWNLA0mfZ+oEEKDa9IWo4Vf80yvgOD7h/JZBXnwtvci4jRSZzG5GNlSeIcnYS\n" + + "Kb5ZoM0NT1+oEk+MmBr1rfFajFgHo1xPI40RCzPXMZy09v9cdyIWSmasweQ2g1lK\n" + + "lTxjqXblKbN6LC3aQw6k9EUQ362yAnE2fV9jdrcEooQOFXfMYLt6RQQ2bPJ21oMZ\n" + + "ODFR54pyUODqvZ02w3rvLKJ3SgoLq++YCQ136+8qbj5zSVsp2QIDAQABMA0GCSqG\n" + + "SIb3DQEBCwUAA4IBAQAR4qLsRAmLc3iNcX2I+YXdHHh1Vmoje2xMELZwpGbXq9LE\n" + + "ozKEQxjSoidwmXwH/m7biH0/X7w1fFgT3ZxgaCVk3BWF+oS691+nQZceORbWYGDg\n" + + "fyyliMT/f25bIfqfqLnk1p6A6RyAGkU5ICPEchDKziX6X4AkbIYXGkcNwi7naSpo\n" + + "VULtcruR7Q3yCnXLJC4hyT7q8dp2GsmUiB/xP5jw2WtxwJZy60Syea0h2e8GEAmn\n" + + "K25CO5bPD/lEVhvwEzY2ZWg7ZMp1FE02fhFbSXpbF9BACy8UsEZ0Pcr0daWUtXTC\n" + + "5xbRhnAbNF0ixcSvZFcZvPhHDSnmnjABuHmuCUAQ\n" + + "-----END CERTIFICATE-----"; + Certificate certificate=convertToCertificate(certificateString); + Mockito.when(keymanagerUtil.convertToCertificate(Mockito.anyString())).thenReturn(certificate); + try{ + keyBindedTokenMatcherUtil.match(input, bindingCertificates, properties); + }catch (IdAuthenticationBusinessException e){ + Assert.assertEquals("IDA-KBT-003",e.getErrorCode()); + } + } + + public static Certificate convertToCertificate(String certData) { + try { + StringReader strReader = new StringReader(certData); + PemReader pemReader = new PemReader(strReader); + PemObject pemObject = pemReader.readPemObject(); + if (Objects.isNull(pemObject)) { + throw new RuntimeException("Invalid certificate"); + } + byte[] certBytes = pemObject.getContent(); + CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + return certFactory.generateCertificate(new ByteArrayInputStream(certBytes)); + } catch (IOException | CertificateException e) { + throw new RuntimeException("Invalid certificate"); + } + } +} diff --git a/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/util/TokenEncoderUtilTest.java b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/util/TokenEncoderUtilTest.java new file mode 100644 index 00000000000..b4b89aa1404 --- /dev/null +++ b/authentication/authentication-common/src/test/java/io/mosip/authentication/common/service/util/TokenEncoderUtilTest.java @@ -0,0 +1,27 @@ +package io.mosip.authentication.common.service.util; + + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +public class TokenEncoderUtilTest { + + + + @Test + public void encodeBase58TestWithVaidDetails_thenPass(){ + String st="string"; + String result=TokenEncoderUtil.encodeBase58(st.getBytes()); + Assert.assertEquals("zVbyBrMk",result); + } + + @Test + public void encodeBase58TestWithNull_thenFail(){ + String st="string"; + String result=TokenEncoderUtil.encodeBase58(null); + } + +} diff --git a/authentication/authentication-core/pom.xml b/authentication/authentication-core/pom.xml index 44dd5f38e1e..db3290c149d 100644 --- a/authentication/authentication-core/pom.xml +++ b/authentication/authentication-core/pom.xml @@ -1,194 +1,194 @@ - - 4.0.0 - - - io.mosip.authentication - authentication-parent - 1.2.0.1-B5 - - 1.2.0.1-B5 - - authentication-core - jar - - authentication-core - Maven project of MOSIP ID-Authentication Core - - - - - io.mosip.kernel - kernel-core - ${kernel-core.version} - - - org.springframework.boot - - spring-boot-starter-security - - - - com.fasterxml.jackson.core - jackson-databind - - - - - - - - commons-codec - commons-codec - ${commons.codec.version} - - - org.apache.commons - commons-lang3 - ${commons.lang.version} - - - - org.springframework.boot - spring-boot-starter-web - ${spring.boot.version} - - - com.fasterxml.jackson.core - jackson-databind - - - - - org.springframework.boot - spring-boot-starter-cache - ${spring.boot.version} - - - - - com.machinezoo.sourceafis - sourceafis - ${sourceafis.version} - - - com.fasterxml.jackson.core - jackson-databind - - - - - - io.mosip.idrepository - id-repository-core - ${id-repository-core.version} - - - io.mosip.kernel - kernel-auth-adapter - - - org.springframework.boot - - spring-boot-starter-security - - - - org.springframework.security - spring-security-test - - - - - io.mosip.kernel - kernel-biosdk-provider - ${kernel-biosdk-provider.version} - - - io.mosip.kernel - kernel-core - - - io.mosip.kernel - kernel-biometrics-api - - - - - io.mosip.kernel - kernel-demographics-api - ${kernel-demoapi.version} - - - com.fasterxml.jackson.core - jackson-databind - - - - - org.springframework.boot - spring-boot-starter-webflux - ${spring.boot.version} - - - com.fasterxml.jackson.core - jackson-databind - - - - - org.springdoc - springdoc-openapi-ui - ${springdoc.version} - - - com.fasterxml.jackson.core - jackson-databind - - - - - io.mosip.kernel - kernel-logger-logback - ${kernel-logger-logback.version} - - - org.springframework.boot - - spring-boot-starter-security - - - - com.fasterxml.jackson.core - jackson-databind - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.module - jackson-module-afterburner - ${jackson.version} - - - io.mosip.kernel - kernel-biometrics-api - ${kernel-biometrics-api.version} - - - io.mosip.kernel - kernel-core - - - com.fasterxml.jackson.core - jackson-databind - - - - - + + 4.0.0 + + + io.mosip.authentication + authentication-parent + 1.2.0.1-SNAPSHOT + + 1.2.0.1-SNAPSHOT + + authentication-core + jar + + authentication-core + Maven project of MOSIP ID-Authentication Core + + + + + io.mosip.kernel + kernel-core + ${kernel-core.version} + + + org.springframework.boot + + spring-boot-starter-security + + + + com.fasterxml.jackson.core + jackson-databind + + + + + + + + commons-codec + commons-codec + ${commons.codec.version} + + + org.apache.commons + commons-lang3 + ${commons.lang.version} + + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + com.fasterxml.jackson.core + jackson-databind + + + + + org.springframework.boot + spring-boot-starter-cache + ${spring.boot.version} + + + + + com.machinezoo.sourceafis + sourceafis + ${sourceafis.version} + + + com.fasterxml.jackson.core + jackson-databind + + + + + + io.mosip.idrepository + id-repository-core + ${id-repository-core.version} + + + io.mosip.kernel + kernel-auth-adapter + + + org.springframework.boot + + spring-boot-starter-security + + + + org.springframework.security + spring-security-test + + + + + io.mosip.kernel + kernel-biosdk-provider + ${kernel-biosdk-provider.version} + + + io.mosip.kernel + kernel-core + + + io.mosip.kernel + kernel-biometrics-api + + + + + io.mosip.kernel + kernel-demographics-api + ${kernel-demoapi.version} + + + com.fasterxml.jackson.core + jackson-databind + + + + + org.springframework.boot + spring-boot-starter-webflux + ${spring.boot.version} + + + com.fasterxml.jackson.core + jackson-databind + + + + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + + + com.fasterxml.jackson.core + jackson-databind + + + + + io.mosip.kernel + kernel-logger-logback + ${kernel-logger-logback.version} + + + org.springframework.boot + + spring-boot-starter-security + + + + com.fasterxml.jackson.core + jackson-databind + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.module + jackson-module-afterburner + ${jackson.version} + + + io.mosip.kernel + kernel-biometrics-api + ${kernel-biometrics-api.version} + + + io.mosip.kernel + kernel-core + + + com.fasterxml.jackson.core + jackson-databind + + + + + diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditEvents.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditEvents.java index f46389d51a8..566996881ca 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditEvents.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditEvents.java @@ -49,6 +49,8 @@ public enum AuditEvents { VCI_EXCHANGE_REQUEST_RESPONSE("IDA_017", "System", "Vci Exchange Request"), + PASSWORD_BASED_AUTH_REQUEST("IDA_018", "System", "Password Based Auth Request"), + /** Static_Pin_Storage_Request_Response. */ STATIC_PIN_STORAGE_REQUEST_RESPONSE("IDA-EVT-OLD-006","BUSINESS", ""),//not applicable for release v1 diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditModules.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditModules.java index f6419cbd278..0069e5c6867 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditModules.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/AuditModules.java @@ -23,6 +23,8 @@ public enum AuditModules { FACE_AUTH("IDA-FAA", "Face Authentication Request", "Face Authenticator"), TOKEN_AUTH("IDA-TOA","Token Authentication requested", "Token Authenticator"), + + PASSWORD_AUTH("IDA-PSD","Password Authentication requested", "Password Authenticator"), /** The e KY C AUTH. */ EKYC_AUTH("IDA-EKA", "E-KYC Authentication Request", "eKYC Authenticator"), diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthCommonConstants.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthCommonConstants.java index 3ef269091ac..5075a446a6f 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthCommonConstants.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthCommonConstants.java @@ -445,6 +445,26 @@ public final class IdAuthCommonConstants { public static final String VC_CREDENTIAL_DEF = "credentialsDefinition"; + public static final String PASSWORD_BASED_AUTH = "PasswordBasedAuth"; + + public static final String PASSWORD = "password"; + + public static final String SALT = "salt"; + + public static final String SEMI_COLON = ";"; + + public static final String OIDC_CLIENT_DATA = "oidc_client_data"; + + public static final String PARTNER_API_KEY_DATA = "partner_api_key_data"; + + public static final String PARTNER_API_KEY_POLICY_ID_DATA = "partner_api_key_policy_id_data"; + + public static final String PARTNER_DATA = "partner_data"; + + public static final String POLICY_DATA = "policy_data"; + + public static final String MISP_LIC_DATA = "misp_lic_data"; + private IdAuthCommonConstants() { } } diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthenticationErrorConstants.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthenticationErrorConstants.java index eefa8d8ca90..5270665766e 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthenticationErrorConstants.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/IdAuthenticationErrorConstants.java @@ -147,6 +147,9 @@ public enum IdAuthenticationErrorConstants { UNAUTHORISED_VCI_EXCHANGE_PARTNER("IDA-MPA-036", "Partner is unauthorised for VCI-Exchange"), VCI_EXCHANGE_NOT_ALLOWED("IDA-MPA-037", "%s not allowed as per policy", "Please try after updating misp policy"), + URI_PATH_PARAMS_MISSING("IDA-MPA-038", "Required Number of Path parameters are missing in URI", + "Please try adding all the required path parameters."), + PARTNER_API_EXPIRED("IDA-MPA-039", "Partner API is expired or using before Commence Start Date."), DATA_VALIDATION_FAILED("IDA-IDV-001", "Input Data Validation Failed"), @@ -203,16 +206,18 @@ public enum IdAuthenticationErrorConstants { PUBLIC_KEY_BINDING_NOT_ALLOWED("IDA-IKB-003", "Publick Key already Binded to another Id."), IDENTITY_NAME_NOT_FOUND("IDA-IKB-004", "Identity Name not found."), CREATE_CERTIFICATE_OBJECT_ERROR("IDA-IKB-005", "Error creating Certificate object."), - TOKEN_AUTH_IDTYPE_MISMATCH("IDA-TOA-001", "Input Identity Type does not match Identity Type of Token Request"), - + KEY_TYPE_NOT_SUPPORT("IDA-VCI-001", "Not Supported JWK Key Type."), CREATE_VCI_PUBLIC_KEY_OBJECT_ERROR("IDA-VCI-002", "Error creating Public Key object."), KEY_ALREADY_MAPPED_ERROR("IDA-VCI-003", "Error Key already mapped to different id/vid."), VCI_NOT_SUPPORTED_ERROR("IDA-VCI-004", "Error VCI not supported."), - LDP_VC_GENERATION_FAILED("IDA-VCI-005", "Ldp VC generation Failed."); + LDP_VC_GENERATION_FAILED("IDA-VCI-005", "Ldp VC generation Failed."), + + PASSWORD_MISMATCH("IDA-PSD-001", "Password value did not match", "Please re-enter your password"), + PASSWORD_MISSING("IDA-PSD-002", "For the input VID/UIN - No Password found in DB.", + "Please use UIN/VID with Password Auth."); - private final String errorCode; private final String errorMessage; private String actionMessage; diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/RequestType.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/RequestType.java index 88733da11a2..870913f7ef8 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/RequestType.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/constant/RequestType.java @@ -21,7 +21,8 @@ public enum RequestType { IDENTITY_KEY_BINDING("IDENTITY-KEY-BINDING","Identity Key Binding Request"), TOKEN_REQUEST("TOKEN-REQUEST", "Token Request"), TOKEN_AUTH("TOKEN-AUTH","Token based Authentication"), - VCI_EXCHANGE_REQUEST("VCI-EXCHANGE-REQUEST","VCI Exchange Request"); + VCI_EXCHANGE_REQUEST("VCI-EXCHANGE-REQUEST","VCI Exchange Request"), + PASSWORD_AUTH("PASSWORD-AUTH","Password Auth"); String type; String message; diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/IdType.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/IdType.java index 5a6eb8861e9..8831f219dd5 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/IdType.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/IdType.java @@ -24,7 +24,8 @@ public enum IdType { /** The uin. */ UIN("UIN"), /** The vid. */ - VID("VID") + VID("VID"), + HANDLE("HANDLE") ; /** diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/KycRequestDTO.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/KycRequestDTO.java index 90c9587478f..02fda3481ad 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/KycRequestDTO.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/indauth/dto/KycRequestDTO.java @@ -10,4 +10,6 @@ public class KycRequestDTO extends RequestDTO { /** H/W or S/W token */ private List keyBindedTokens; + + private String password; } diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/ComparePasswordFunction.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/ComparePasswordFunction.java new file mode 100644 index 00000000000..41464cc05bb --- /dev/null +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/ComparePasswordFunction.java @@ -0,0 +1,22 @@ +package io.mosip.authentication.core.spi.indauth.match; + +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; + +/** + * To match Password against Stored Hashed Password and Salt + + */ +public interface ComparePasswordFunction { + + /** + * To Match Password. + * + * @param passwordValue the password value + * @param passwordHashValue the stored password hash value + * @param salt the stored salt value + * @return true, if successful + * @throws IdAuthenticationBusinessException the id authentication business exception + */ + public boolean matchPasswordFunction(String passwordValue, String passwordHashValue, String salt) throws IdAuthenticationBusinessException; + +} diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/IdInfoFetcher.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/IdInfoFetcher.java index 92c1585159b..237e97b6a22 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/IdInfoFetcher.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/IdInfoFetcher.java @@ -1,241 +1,261 @@ -package io.mosip.authentication.core.spi.indauth.match; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.springframework.core.env.Environment; - -import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; -import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; -import io.mosip.authentication.core.indauth.dto.RequestDTO; -import io.mosip.authentication.core.spi.bioauth.CbeffDocType; -import io.mosip.authentication.core.util.DemoMatcherUtil; -import io.mosip.authentication.core.util.DemoNormalizer; - -/** - * The IdInfoFetcher interface that provides the helper methods invoked by the - * classes involved in ID Info matching. - * - * @author Loganathan.Sekar - * @author Nagarjuna - */ -public interface IdInfoFetcher { - - /** - * Gets the template default language codes - * @return - */ - public List getTemplatesDefaultLanguageCodes(); - - /** - * Gets the system supported languages. - * Combination of Mandatory and optional languages. - * @return - */ - public List getSystemSupportedLanguageCodes(); - - /** - * To check language type. - * - * @param languageForMatchType the language for match type - * @param languageFromReq the language from req - * @return true, if successful - */ - public boolean checkLanguageType(String languageForMatchType, String languageFromReq); - - /** - * Get language name for Match Properties based on language code. - * - * @param languageCode language code - * @return language name - */ - public Optional getLanguageName(String languageCode); - - /** - * Gets the identity info for the MatchType from the IdentityDTO. - * - * @param matchType the match type - * @param idName - * @param identity the identity - * @param language the language - * @return the identity info - */ - public Map getIdentityRequestInfo(MatchType matchType, String idName, RequestDTO identity, String language); - - /** - * Gets the identity info. - * - * @param matchType the match type - * @param idName the id name - * @param identity the identity - * @return the identity info - */ - public Map> getIdentityInfo(MatchType matchType, String idName, RequestDTO identity); - - /** - * Gets the identity info for the MatchType from the IdentityDTO. - * - * @param matchType the match type - * @param idName - * @param identity the identity - * @param language the language - * @return the identity info - */ - public Map getIdentityRequestInfo(MatchType matchType, RequestDTO identity, String language); - - /** - * Get the Validate Otp function. - * - * @return the ValidateOtpFunction - */ - public ValidateOtpFunction getValidateOTPFunction(); - - /** - * To fetch cbeff values. - * - * @param idEntity the id entity - * @param cbeffDocTypes the cbeff doc types - * @param matchType the match type - * @return the cbeff values - * @throws IdAuthenticationBusinessException the id authentication business exception - */ - public Map>> getCbeffValues(Map> idEntity, - CbeffDocType[] cbeffDocTypes, MatchType matchType) throws IdAuthenticationBusinessException; - - /** - * To get EnvPropertyResolver. - * - * @return the environment - */ - public Environment getEnvironment(); - - /** - * Title info fetcher from Master data manager. - * - * @return the title fetcher - */ - public MasterDataFetcher getTitleFetcher(); - - /** - * Gets the matching threshold. - * - * @param key the key - * @return the matching threshold - */ - public Optional getMatchingThreshold(String key); - - - /** - * Gets the demo normalizer object to normalise the - * corresponding(address/name) used for demographic authentication - * . - * - * @return the demo normalizer - */ - public DemoNormalizer getDemoNormalizer(); - - /** - * Gets the user preferred language attribute - * @return - */ - public List getUserPreferredLanguages(Map> idInfo); - - - /** - * Gets the match function. - * - * @param authType the auth type - * @return the match function - */ - public TriFunctionWithBusinessException, Map, Map, Double> getMatchFunction(AuthType authType); - - - /** - * Gets the type for id name. - * - * @param idName the id name - * @param idMappings the id mappings - * @return the type for id name - */ - public Optional getTypeForIdName(String idName, IdMapping[] idMappings); - - /** - * Gets the mapping config. - * - * @return the mapping config - */ - public MappingConfig getMappingConfig(); - - /** - * - * @return - */ - public DemoMatcherUtil getDemoMatcherUtil(); - - - /** - * Gets the available dynamic attributes names. - * - * @param request the request - * @return the available dynamic attributes names - */ - Set getAvailableDynamicAttributesNames(RequestDTO request); - - /** - * Fetch data from Identity info value based on Identity response. - * - * @param idResponseDTO the id response DTO - * @return the id info - * @throws IdAuthenticationBusinessException the id authentication business exception - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Map> getIdInfo(Map idResponseDTO) { - return idResponseDTO.entrySet().stream().flatMap(entry -> { - if (entry.getValue() instanceof Map) { - return ((Map) entry.getValue()).entrySet().stream(); - } else { - return Stream.of(entry); - } - }).collect(Collectors.toMap(t -> t.getKey(), entry -> { - Object val = entry.getValue(); - if (val instanceof List) { - List arrayList = (List) val; - if (!arrayList.isEmpty()) { - Object object = arrayList.get(0); - if (object instanceof Map) { - return arrayList.stream().filter(elem -> elem instanceof Map) - .map(elem -> (Map) elem).map(map1 -> { - String value = String.valueOf(map1.get("value")); - IdentityInfoDTO idInfo = new IdentityInfoDTO(); - if (map1.containsKey("language")) { - idInfo.setLanguage(String.valueOf(map1.get("language"))); - } - idInfo.setValue(value); - return idInfo; - }).collect(Collectors.toList()); - - } else if (object instanceof String) { - return arrayList.stream().map(string -> { - String value = (String) string; - IdentityInfoDTO idInfo = new IdentityInfoDTO(); - idInfo.setValue(value); - return idInfo; - }).collect(Collectors.toList()); - } - } - } else if (val instanceof Boolean || val instanceof String || val instanceof Long || val instanceof Integer - || val instanceof Double || val instanceof Float) { - IdentityInfoDTO idInfo = new IdentityInfoDTO(); - idInfo.setValue(String.valueOf(val)); - return Stream.of(idInfo).collect(Collectors.toList()); - } - return Collections.emptyList(); - })); - } -} +package io.mosip.authentication.core.spi.indauth.match; + +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.PASSWORD; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.SEMI_COLON; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.COLON; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.springframework.core.env.Environment; + +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; +import io.mosip.authentication.core.indauth.dto.RequestDTO; +import io.mosip.authentication.core.spi.bioauth.CbeffDocType; +import io.mosip.authentication.core.util.DemoMatcherUtil; +import io.mosip.authentication.core.util.DemoNormalizer; + +/** + * The IdInfoFetcher interface that provides the helper methods invoked by the + * classes involved in ID Info matching. + * + * @author Loganathan.Sekar + * @author Nagarjuna + */ +public interface IdInfoFetcher { + + /** + * Gets the template default language codes + * @return + */ + public List getTemplatesDefaultLanguageCodes(); + + /** + * Gets the system supported languages. + * Combination of Mandatory and optional languages. + * @return + */ + public List getSystemSupportedLanguageCodes(); + + /** + * To check language type. + * + * @param languageForMatchType the language for match type + * @param languageFromReq the language from req + * @return true, if successful + */ + public boolean checkLanguageType(String languageForMatchType, String languageFromReq); + + /** + * Get language name for Match Properties based on language code. + * + * @param languageCode language code + * @return language name + */ + public Optional getLanguageName(String languageCode); + + /** + * Gets the identity info for the MatchType from the IdentityDTO. + * + * @param matchType the match type + * @param idName + * @param identity the identity + * @param language the language + * @return the identity info + */ + public Map getIdentityRequestInfo(MatchType matchType, String idName, RequestDTO identity, String language); + + /** + * Gets the identity info. + * + * @param matchType the match type + * @param idName the id name + * @param identity the identity + * @return the identity info + */ + public Map> getIdentityInfo(MatchType matchType, String idName, RequestDTO identity); + + /** + * Gets the identity info for the MatchType from the IdentityDTO. + * + * @param matchType the match type + * @param idName + * @param identity the identity + * @param language the language + * @return the identity info + */ + public Map getIdentityRequestInfo(MatchType matchType, RequestDTO identity, String language); + + /** + * Get the Validate Otp function. + * + * @return the ValidateOtpFunction + */ + public ValidateOtpFunction getValidateOTPFunction(); + + /** + * To fetch cbeff values. + * + * @param idEntity the id entity + * @param cbeffDocTypes the cbeff doc types + * @param matchType the match type + * @return the cbeff values + * @throws IdAuthenticationBusinessException the id authentication business exception + */ + public Map>> getCbeffValues(Map> idEntity, + CbeffDocType[] cbeffDocTypes, MatchType matchType) throws IdAuthenticationBusinessException; + + /** + * To get EnvPropertyResolver. + * + * @return the environment + */ + public Environment getEnvironment(); + + /** + * Title info fetcher from Master data manager. + * + * @return the title fetcher + */ + public MasterDataFetcher getTitleFetcher(); + + /** + * Gets the matching threshold. + * + * @param key the key + * @return the matching threshold + */ + public Optional getMatchingThreshold(String key); + + + /** + * Gets the demo normalizer object to normalise the + * corresponding(address/name) used for demographic authentication + * . + * + * @return the demo normalizer + */ + public DemoNormalizer getDemoNormalizer(); + + /** + * Gets the user preferred language attribute + * @return + */ + public List getUserPreferredLanguages(Map> idInfo); + + + /** + * Gets the match function. + * + * @param authType the auth type + * @return the match function + */ + public TriFunctionWithBusinessException, Map, Map, Double> getMatchFunction(AuthType authType); + + + /** + * Gets the type for id name. + * + * @param idName the id name + * @param idMappings the id mappings + * @return the type for id name + */ + public Optional getTypeForIdName(String idName, IdMapping[] idMappings); + + /** + * Gets the mapping config. + * + * @return the mapping config + */ + public MappingConfig getMappingConfig(); + + /** + * + * @return + */ + public DemoMatcherUtil getDemoMatcherUtil(); + + + /** + * Gets the available dynamic attributes names. + * + * @param request the request + * @return the available dynamic attributes names + */ + Set getAvailableDynamicAttributesNames(RequestDTO request); + + /** + * Fetch data from Identity info value based on Identity response. + * + * @param idResponseDTO the id response DTO + * @return the id info + * @throws IdAuthenticationBusinessException the id authentication business exception + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static Map> getIdInfo(Map idResponseDTO) { + return idResponseDTO.entrySet().stream().flatMap(entry -> { + if (entry.getValue() instanceof Map) { + return ((Map) entry.getValue()).entrySet().stream(); + } else { + return Stream.of(entry); + } + }).collect(Collectors.toMap(t -> t.getKey(), entry -> { + Object val = entry.getValue(); + if (val instanceof List) { + List arrayList = (List) val; + if (!arrayList.isEmpty()) { + Object object = arrayList.get(0); + if (object instanceof Map) { + return arrayList.stream().filter(elem -> elem instanceof Map) + .map(elem -> (Map) elem).map(map1 -> { + String value = String.valueOf(map1.get("value")); + IdentityInfoDTO idInfo = new IdentityInfoDTO(); + if (map1.containsKey("language")) { + idInfo.setLanguage(String.valueOf(map1.get("language"))); + } + idInfo.setValue(value); + return idInfo; + }).collect(Collectors.toList()); + + } else if (object instanceof String) { + return arrayList.stream().map(string -> { + String value = (String) string; + IdentityInfoDTO idInfo = new IdentityInfoDTO(); + idInfo.setValue(value); + return idInfo; + }).collect(Collectors.toList()); + } + } + } else if (val instanceof Boolean || val instanceof String || val instanceof Long || val instanceof Integer + || val instanceof Double || val instanceof Float) { + IdentityInfoDTO idInfo = new IdentityInfoDTO(); + idInfo.setValue(String.valueOf(val)); + return Stream.of(idInfo).collect(Collectors.toList()); + } else if (entry.getKey().equals(PASSWORD) && val instanceof Map) { + Map map = (Map) val; + String passwordData = map.entrySet().stream() + .map(mapEntry -> mapEntry.getKey().trim() + String.valueOf(COLON) + mapEntry.getValue().trim()) + .collect(Collectors.joining(SEMI_COLON)); + IdentityInfoDTO idInfo = new IdentityInfoDTO(); + idInfo.setValue(String.valueOf(passwordData)); + return Stream.of(idInfo).collect(Collectors.toList()); + } + + return Collections.emptyList(); + })); + } + + /** + * To Get match Password function. + * + * @return the ComparePasswordFunction + */ + public ComparePasswordFunction getMatchPasswordFunction(); +} diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MappingConfig.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MappingConfig.java index 4f8e57e2fef..b7281c5acb8 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MappingConfig.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MappingConfig.java @@ -1,245 +1,252 @@ -package io.mosip.authentication.core.spi.indauth.match; - -import java.util.List; -import java.util.Map; - -/** - * The Interface MappingConfig. - * - * @author Dinesh Karuppiah.T - */ - -public interface MappingConfig { - - /** - * List of value to hold Full Name. - * - * @return the name - */ - public List getName(); - - /** - * List of value to hold DOB. - * - * @return the dob - */ - public List getDob(); - - /** - * List of value to hold DOBtype. - * - * @return the dob type - */ - public List getDobType(); - - /** - * List of value to hold Age. - * - * @return the age - */ - public List getAge(); - - /** - * List of value to hold Gender. - * - * @return the gender - */ - public List getGender(); - - /** - * List of value to hold Phone Number. - * - * @return the phone number - */ - public List getPhoneNumber(); - - /** - * List of value to hold Email ID. - * - * @return the email id - */ - public List getEmailId(); - - /** - * List of value to hold Address Line 1. - * - * @return the address line 1 - */ - public List getAddressLine1(); - - /** - * List of value to hold Address Line 2. - * - * @return the address line 2 - */ - public List getAddressLine2(); - - /** - * List of value to hold Address Line 3. - * - * @return the address line 3 - */ - public List getAddressLine3(); - - /** - * List of value to hold Location 1. - * - * @return the location 1 - */ - public List getLocation1(); - - /** - * List of value to hold Location 2. - * - * @return the location 2 - */ - public List getLocation2(); - - /** - * List of value to hold Location 3. - * - * @return the location 3 - */ - public List getLocation3(); - - /** - * List of value to hold Postalcode. - * - * @return the pin code - */ - public List getPostalCode(); - - /** - * List of value to hold Full Address. - * - * @return the full address - */ - public List getFullAddress(); - - /** - * List of value to hold Otp. - * - * @return the otp - */ - public List getOtp(); - - /** - * List of value to hold Pin. - * - * @return the pin - */ - public List getPin(); - - /** - * List of value to hold IRIS. - * - * @return the iris - */ - public List getIris(); - - /** - * List of value to hold Left Index. - * - * @return the left index - */ - - public List getLeftIndex(); - - /** - * List of value to hold Left Little. - * - * @return the left little - */ - public List getLeftLittle(); - - /** - * List of value to hold Left Middle. - * - * @return the left middle - */ - public List getLeftMiddle(); - - /** - * List of value to hold Left Ring. - * - * @return the left ring - */ - public List getLeftRing(); - - /** - * List of value to hold Left Thumb. - * - * @return the left thumb - */ - public List getLeftThumb(); - - /** - * List of value to hold Right Index. - * - * @return the right index - */ - public List getRightIndex(); - - /** - * List of value to hold Right Little. - * - * @return the right little - */ - public List getRightLittle(); - - /** - * List of value to hold Right Middle. - * - * @return the right middle - */ - public List getRightMiddle(); - - /** - * List of value to hold Right Ring. - * - * @return the right ring - */ - public List getRightRing(); - - /** - * List of value to hold Right Thumb. - * - * @return the right thumb - */ - public List getRightThumb(); - - /** - * List of value to hold Finger print. - * - * @return the fingerprint - */ - public List getFingerprint(); - - /** - * List of value to hold Face. - * - * @return the face - */ - public List getFace(); - - /** - * Gets the left eye. - * - * @return the left eye - */ - public List getLeftEye(); - - /** - * Gets the right eye. - * - * @return the right eye - */ - public List getRightEye(); - - /** - * Gets the dynamic attributes. - * - * @return the dynamic attributes - */ - public Map> getDynamicAttributes(); -} +package io.mosip.authentication.core.spi.indauth.match; + +import java.util.List; +import java.util.Map; + +/** + * The Interface MappingConfig. + * + * @author Dinesh Karuppiah.T + */ + +public interface MappingConfig { + + /** + * List of value to hold Full Name. + * + * @return the name + */ + public List getName(); + + /** + * List of value to hold DOB. + * + * @return the dob + */ + public List getDob(); + + /** + * List of value to hold DOBtype. + * + * @return the dob type + */ + public List getDobType(); + + /** + * List of value to hold Age. + * + * @return the age + */ + public List getAge(); + + /** + * List of value to hold Gender. + * + * @return the gender + */ + public List getGender(); + + /** + * List of value to hold Phone Number. + * + * @return the phone number + */ + public List getPhoneNumber(); + + /** + * List of value to hold Email ID. + * + * @return the email id + */ + public List getEmailId(); + + /** + * List of value to hold Address Line 1. + * + * @return the address line 1 + */ + public List getAddressLine1(); + + /** + * List of value to hold Address Line 2. + * + * @return the address line 2 + */ + public List getAddressLine2(); + + /** + * List of value to hold Address Line 3. + * + * @return the address line 3 + */ + public List getAddressLine3(); + + /** + * List of value to hold Location 1. + * + * @return the location 1 + */ + public List getLocation1(); + + /** + * List of value to hold Location 2. + * + * @return the location 2 + */ + public List getLocation2(); + + /** + * List of value to hold Location 3. + * + * @return the location 3 + */ + public List getLocation3(); + + /** + * List of value to hold Postalcode. + * + * @return the pin code + */ + public List getPostalCode(); + + /** + * List of value to hold Full Address. + * + * @return the full address + */ + public List getFullAddress(); + + /** + * List of value to hold Otp. + * + * @return the otp + */ + public List getOtp(); + + /** + * List of value to hold Pin. + * + * @return the pin + */ + public List getPin(); + + /** + * List of value to hold IRIS. + * + * @return the iris + */ + public List getIris(); + + /** + * List of value to hold Left Index. + * + * @return the left index + */ + + public List getLeftIndex(); + + /** + * List of value to hold Left Little. + * + * @return the left little + */ + public List getLeftLittle(); + + /** + * List of value to hold Left Middle. + * + * @return the left middle + */ + public List getLeftMiddle(); + + /** + * List of value to hold Left Ring. + * + * @return the left ring + */ + public List getLeftRing(); + + /** + * List of value to hold Left Thumb. + * + * @return the left thumb + */ + public List getLeftThumb(); + + /** + * List of value to hold Right Index. + * + * @return the right index + */ + public List getRightIndex(); + + /** + * List of value to hold Right Little. + * + * @return the right little + */ + public List getRightLittle(); + + /** + * List of value to hold Right Middle. + * + * @return the right middle + */ + public List getRightMiddle(); + + /** + * List of value to hold Right Ring. + * + * @return the right ring + */ + public List getRightRing(); + + /** + * List of value to hold Right Thumb. + * + * @return the right thumb + */ + public List getRightThumb(); + + /** + * List of value to hold Finger print. + * + * @return the fingerprint + */ + public List getFingerprint(); + + /** + * List of value to hold Face. + * + * @return the face + */ + public List getFace(); + + /** + * Gets the left eye. + * + * @return the left eye + */ + public List getLeftEye(); + + /** + * Gets the right eye. + * + * @return the right eye + */ + public List getRightEye(); + + /** + * Gets the dynamic attributes. + * + * @return the dynamic attributes + */ + public Map> getDynamicAttributes(); + + /** + * List of value to hold password. + * + * @return the password + */ + public List getPassword(); +} diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MatchType.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MatchType.java index cc4d4343e12..81f8bbe8d52 100644 --- a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MatchType.java +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/match/MatchType.java @@ -41,7 +41,9 @@ public enum Category { /** s-pin category. */ SPIN("pin"), /** Token category */ - KBT("kbt"); + KBT("kbt"), + /** Password category */ + PWD("pwd"); /** The type. */ String type; diff --git a/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/service/PasswordAuthService.java b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/service/PasswordAuthService.java new file mode 100644 index 00000000000..7b22ba59bf6 --- /dev/null +++ b/authentication/authentication-core/src/main/java/io/mosip/authentication/core/spi/indauth/service/PasswordAuthService.java @@ -0,0 +1,4 @@ +package io.mosip.authentication.core.spi.indauth.service; + +public interface PasswordAuthService extends AuthService { +} 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 4767aa7dba8..7cb5386510a 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 @@ -1,8 +1,14 @@ package io.mosip.authentication.core.util; +import java.util.Map; import java.util.Objects; +import io.mosip.authentication.core.logger.IdaLogger; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import io.mosip.authentication.core.constant.IdAuthCommonConstants; @@ -11,6 +17,8 @@ import io.mosip.authentication.core.indauth.dto.IdType; import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; +import static io.mosip.authentication.core.constant.IdAuthCommonConstants.SESSION_ID; + /** * @author Manoj SP * @author Nagarjuna @@ -19,9 +27,14 @@ @Component public class IdTypeUtil { + private static Logger mosipLogger = IdaLogger.getLogger(IdTypeUtil.class); + @Autowired IdValidationUtil idValidator; + @Value("#{${mosip.ida.handle-types.regex}}") + private Map handleTypesRegex; + public boolean validateUin(String uin) { try { if (Objects.nonNull(idValidator)) @@ -44,11 +57,36 @@ public boolean validateVid(String vid) { } } + public boolean validateHandle(String handle) { + try { + if(Objects.nonNull(handleTypesRegex)) { + if(StringUtils.isEmpty(handle)) + return false; + + int index = handle.lastIndexOf("@"); + if(index <= 0) + return false; + + String handleType = handle.substring(index); + if(!handleTypesRegex.containsKey(handleType)) + return false; + + return handle.matches(handleTypesRegex.get(handleType)); + } + } catch (BaseUncheckedException e) { + mosipLogger.error(SESSION_ID, this.getClass().getSimpleName(), "VALIDATE_HANDLE", + "Failed to validate handle >> "+ e.getMessage()); + } + return false; + } + public IdType getIdType(String id) throws IdAuthenticationBusinessException { if (this.validateUin(id)) return IdType.UIN; if (this.validateVid(id)) return IdType.VID; + if (this.validateHandle(id)) + return IdType.HANDLE; throw new IdAuthenticationBusinessException( IdAuthenticationErrorConstants.INVALID_INPUT_PARAMETER.getErrorCode(), String.format(IdAuthenticationErrorConstants.INVALID_INPUT_PARAMETER.getErrorMessage(), diff --git a/authentication/authentication-filter-api/pom.xml b/authentication/authentication-filter-api/pom.xml index e6fe9dbe601..0812ac79ab3 100644 --- a/authentication/authentication-filter-api/pom.xml +++ b/authentication/authentication-filter-api/pom.xml @@ -4,9 +4,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-filter-api authentication-filter-api ID Authentication Filter API diff --git a/authentication/authentication-filter-api/src/test/java/io/mosip/authentication/authfilter/exception/IdAuthenticationFilterExceptionTest.java b/authentication/authentication-filter-api/src/test/java/io/mosip/authentication/authfilter/exception/IdAuthenticationFilterExceptionTest.java new file mode 100644 index 00000000000..c525d580e24 --- /dev/null +++ b/authentication/authentication-filter-api/src/test/java/io/mosip/authentication/authfilter/exception/IdAuthenticationFilterExceptionTest.java @@ -0,0 +1,33 @@ +package io.mosip.authentication.authfilter.exception; + +import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants; +import org.junit.Test; + +public class IdAuthenticationFilterExceptionTest { + + @Test(expected= IdAuthenticationFilterException.class) + public void IdAuthenticationFilterException() throws IdAuthenticationFilterException { + throw new IdAuthenticationFilterException(); + } + + @Test(expected=IdAuthenticationFilterException.class) + public void IdAuthenticationFilterException2args() throws IdAuthenticationFilterException { + throw new IdAuthenticationFilterException("errorcode", "errormessage"); + } + + @Test(expected=IdAuthenticationFilterException.class) + public void IdAuthenticationFilterException3args() throws IdAuthenticationFilterException { + throw new IdAuthenticationFilterException("errorcode", "errormessage", null); + } + + @Test(expected=IdAuthenticationFilterException.class) + public void IdAuthenticationFilterExceptionEnum() throws IdAuthenticationFilterException { + throw new IdAuthenticationFilterException(IdAuthenticationErrorConstants.OTP_GENERATION_FAILED); + } + + @Test(expected=IdAuthenticationFilterException.class) + public void IdAuthenticationFilterExceptionEnumThrowable() throws IdAuthenticationFilterException { + throw new IdAuthenticationFilterException(IdAuthenticationErrorConstants.OTP_GENERATION_FAILED, null); + } + +} diff --git a/authentication/authentication-filter-api/src/test/java/io/mosip/authentication/authfilter/exception/InvalidAuthFilterJarSignatureExceptionTest.java b/authentication/authentication-filter-api/src/test/java/io/mosip/authentication/authfilter/exception/InvalidAuthFilterJarSignatureExceptionTest.java new file mode 100644 index 00000000000..17999eaaff2 --- /dev/null +++ b/authentication/authentication-filter-api/src/test/java/io/mosip/authentication/authfilter/exception/InvalidAuthFilterJarSignatureExceptionTest.java @@ -0,0 +1,33 @@ +package io.mosip.authentication.authfilter.exception; + +import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants; +import org.junit.Test; + +public class InvalidAuthFilterJarSignatureExceptionTest { + + @Test(expected= InvalidAuthFilterJarSignatureException.class) + public void InvalidAuthFilterJarSignatureException() throws InvalidAuthFilterJarSignatureException { + throw new InvalidAuthFilterJarSignatureException(); + } + + @Test(expected=InvalidAuthFilterJarSignatureException.class) + public void InvalidAuthFilterJarSignatureException2args() throws InvalidAuthFilterJarSignatureException { + throw new InvalidAuthFilterJarSignatureException("errorcode", "errormessage"); + } + + @Test(expected=InvalidAuthFilterJarSignatureException.class) + public void InvalidAuthFilterJarSignatureException3args() throws InvalidAuthFilterJarSignatureException { + throw new InvalidAuthFilterJarSignatureException("errorcode", "errormessage", null); + } + + @Test(expected=InvalidAuthFilterJarSignatureException.class) + public void InvalidAuthFilterJarSignatureExceptionEnum() throws InvalidAuthFilterJarSignatureException { + throw new InvalidAuthFilterJarSignatureException(IdAuthenticationErrorConstants.OTP_GENERATION_FAILED); + } + + @Test(expected=InvalidAuthFilterJarSignatureException.class) + public void InvalidAuthFilterJarSignatureExceptionEnumThrowable() throws InvalidAuthFilterJarSignatureException { + throw new InvalidAuthFilterJarSignatureException(IdAuthenticationErrorConstants.OTP_GENERATION_FAILED, null); + } + +} diff --git a/authentication/authentication-hotlistfilter-impl/pom.xml b/authentication/authentication-hotlistfilter-impl/pom.xml index 56c241dbbb4..3d3b1e833ac 100644 --- a/authentication/authentication-hotlistfilter-impl/pom.xml +++ b/authentication/authentication-hotlistfilter-impl/pom.xml @@ -4,9 +4,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-hotlistfilter-impl authentication-hotlistfilter-impl ID Authentication Filter Implementation for Hotlist validation diff --git a/authentication/authentication-internal-service/Dockerfile b/authentication/authentication-internal-service/Dockerfile index 7e27c6b8402..acf26219f82 100644 --- a/authentication/authentication-internal-service/Dockerfile +++ b/authentication/authentication-internal-service/Dockerfile @@ -1,142 +1,144 @@ -FROM openjdk:11 - -ARG SOURCE -ARG COMMIT_HASH -ARG COMMIT_ID -ARG BUILD_TIME -LABEL source=${SOURCE} -LABEL commit_hash=${COMMIT_HASH} -LABEL commit_id=${COMMIT_ID} -LABEL build_time=${BUILD_TIME} - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -#ARG bio_sdk_folder=mock/0.9 -ARG biosdk_zip_path - -ARG demosdk_zip_path - -# can be passed during Docker build as build time environment for hsm client zip file path -#ARG client_zip_path -ARG hsm_client_zip_path - -# can be passed during Docker build as build time environment for glowroot -ARG is_glowroot - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass glowroot, at docker runtime -ENV is_glowroot_env=${is_glowroot} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# environment variable to pass iam_adapter url, at docker runtime -ENV iam_adapter_url_env=${iam_adapter_url} - -#ENV bio_sdk_folder_env=${bio_sdk_folder} -ENV biosdk_zip_file_path=${biosdk_zip_path} - -ENV demosdk_zip_file_path=${demosdk_zip_path} - -# environment variable to pass hsm client zip file path, at docker runtime -#ENV zip_file_path=${client_zip_path} -ENV hsm_zip_file_path=${hsm_client_zip_path} - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_group=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_uid=1001 - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_gid=1001 - -ARG hsm_local_dir=hsm-client - -ENV hsm_local_dir_name=${hsm_local_dir} - -ARG biosdk_local_dir=biosdk-client - -ARG demosdk_local_dir=demosdk - -ENV biosdk_local_dir_name=${biosdk_local_dir} - -ENV demosdk_local_dir_name=${demosdk_local_dir} - -# install packages and create user -RUN apt-get -y update \ -&& apt-get install -y unzip sudo \ -&& groupadd -g ${container_user_gid} ${container_user_group} \ -&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ -&& adduser ${container_user} sudo \ -&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers \ -&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${biosdk_local_dir}/install.sh" >> /etc/sudoers - -# set working directory for the user -WORKDIR /home/${container_user} - -ENV work_dir=/home/${container_user} - -ARG loader_path=${work_dir}/additional_jars/ - -RUN mkdir -p ${loader_path} - -ENV loader_path_env=${loader_path} - -ENV current_module_env=authentication-internal-service - -ADD configure_start.sh configure_start.sh - -RUN chmod +x configure_start.sh - -ADD target/${current_module_env}-*.jar ${current_module_env}.jar - -EXPOSE 8093 - -EXPOSE 9010 - -# change permissions of file inside working dir -RUN chown -R ${container_user}:${container_user} /home/${container_user} - -# select container user for all tasks -USER ${container_user_uid}:${container_user_gid} - -ENTRYPOINT [ "./configure_start.sh" ] - -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - sed -i "s//${current_module_env}/g" glowroot/glowroot.properties ; \ - wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Djava.security.debug=sunpkcs11 -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ - else \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ - wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Djava.security.debug=sunpkcs11 -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ - fi - -#Sample docker run command: -# sudo docker run --rm -it -e artifactory_url_env="http://artifactory" -e spring_config_label_env="1.0.9" -e active_profile_env="dev" -e spring_config_url_env="http://config-server/config" -e PKCS11_PROXY_SOCKET=tcp://softhsm-ida:5666 -p 8093:8093 authentication-internal-service:1.0.9 \ No newline at end of file +FROM openjdk:11 + +ARG SOURCE +ARG COMMIT_HASH +ARG COMMIT_ID +ARG BUILD_TIME +LABEL source=${SOURCE} +LABEL commit_hash=${COMMIT_HASH} +LABEL commit_id=${COMMIT_ID} +LABEL build_time=${BUILD_TIME} + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG spring_config_label + +# can be passed during Docker build as build time environment for spring profiles active +ARG active_profile + +# can be passed during Docker build as build time environment for config server URL +ARG spring_config_url + +#ARG bio_sdk_folder=mock/0.9 +ARG biosdk_zip_path + +ARG demosdk_zip_path + +# can be passed during Docker build as build time environment for hsm client zip file path +#ARG client_zip_path +ARG hsm_client_zip_path + +# can be passed during Docker build as build time environment for glowroot +ARG is_glowroot + +# can be passed during Docker build as build time environment for artifactory URL +ARG artifactory_url + +# environment variable to pass active profile such as DEV, QA etc at docker runtime +ENV active_profile_env=${active_profile} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass spring configuration url, at docker runtime +ENV spring_config_url_env=${spring_config_url} + +# environment variable to pass glowroot, at docker runtime +ENV is_glowroot_env=${is_glowroot} + +# environment variable to pass artifactory url, at docker runtime +ENV artifactory_url_env=${artifactory_url} + +# environment variable to pass iam_adapter url, at docker runtime +ENV iam_adapter_url_env=${iam_adapter_url} + +#ENV bio_sdk_folder_env=${bio_sdk_folder} +ENV biosdk_zip_file_path=${biosdk_zip_path} + +ENV demosdk_zip_file_path=${demosdk_zip_path} + +# environment variable to pass hsm client zip file path, at docker runtime +#ENV zip_file_path=${client_zip_path} +ENV hsm_zip_file_path=${hsm_client_zip_path} + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_group=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_uid=1001 + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_gid=1001 + +ARG hsm_local_dir=hsm-client + +ENV hsm_local_dir_name=${hsm_local_dir} + +ARG biosdk_local_dir=biosdk-client + +ARG demosdk_local_dir=demosdk + +ENV biosdk_local_dir_name=${biosdk_local_dir} + +ENV demosdk_local_dir_name=${demosdk_local_dir} + +# install packages and create user +RUN apt-get -y update \ +&& apt-get install -y unzip sudo \ +&& groupadd -g ${container_user_gid} ${container_user_group} \ +&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ +&& adduser ${container_user} sudo \ +&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers \ +&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${biosdk_local_dir}/install.sh" >> /etc/sudoers + +# set working directory for the user +WORKDIR /home/${container_user} + +ENV work_dir=/home/${container_user} + +ARG loader_path=${work_dir}/additional_jars/ + +RUN mkdir -p ${loader_path} + +ENV loader_path_env=${loader_path} + +ENV current_module_env=authentication-internal-service + +ADD configure_start.sh configure_start.sh + +ADD ./lib/* "${loader_path_env}"/ + +RUN chmod +x configure_start.sh + +ADD target/${current_module_env}-*.jar ${current_module_env}.jar + +EXPOSE 8093 + +EXPOSE 9010 + +# change permissions of file inside working dir +RUN chown -R ${container_user}:${container_user} /home/${container_user} + +# select container user for all tasks +USER ${container_user_uid}:${container_user_gid} + +ENTRYPOINT [ "./configure_start.sh" ] + +CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ + unzip glowroot.zip ; \ + rm -rf glowroot.zip ; \ + sed -i "s//${current_module_env}/g" glowroot/glowroot.properties ; \ + wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -jar -Djava.security.debug=sunpkcs11 -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ + else \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ + wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -jar -Djava.security.debug=sunpkcs11 -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ + fi + +#Sample docker run command: +# sudo docker run --rm -it -e artifactory_url_env="http://artifactory" -e spring_config_label_env="1.0.9" -e active_profile_env="dev" -e spring_config_url_env="http://config-server/config" -e PKCS11_PROXY_SOCKET=tcp://softhsm-ida:5666 -p 8093:8093 authentication-internal-service:1.0.9 diff --git a/authentication/authentication-internal-service/lib/libargon2.so b/authentication/authentication-internal-service/lib/libargon2.so new file mode 100755 index 00000000000..bf8cad86215 Binary files /dev/null and b/authentication/authentication-internal-service/lib/libargon2.so differ diff --git a/authentication/authentication-internal-service/pom.xml b/authentication/authentication-internal-service/pom.xml index 46aa9b62574..86e252e2399 100644 --- a/authentication/authentication-internal-service/pom.xml +++ b/authentication/authentication-internal-service/pom.xml @@ -7,9 +7,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-internal-service authentication-internal-service 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 169c4a4feb6..808ad5a3ffd 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 @@ -31,6 +31,7 @@ import io.mosip.authentication.common.service.impl.KeyBindedTokenAuthServiceImpl; import io.mosip.authentication.common.service.impl.OTPAuthServiceImpl; import io.mosip.authentication.common.service.impl.OTPServiceImpl; +import io.mosip.authentication.common.service.impl.PasswordAuthServiceImpl; import io.mosip.authentication.common.service.impl.hotlist.HotlistServiceImpl; import io.mosip.authentication.common.service.impl.idevent.CredentialStoreServiceImpl; import io.mosip.authentication.common.service.impl.idevent.IdChangeEventHandlerServiceImpl; @@ -46,6 +47,7 @@ import io.mosip.authentication.common.service.integration.NotificationManager; import io.mosip.authentication.common.service.integration.OTPManager; import io.mosip.authentication.common.service.integration.PartnerServiceManager; +import io.mosip.authentication.common.service.integration.PasswordComparator; import io.mosip.authentication.common.service.integration.TokenIdManager; import io.mosip.authentication.common.service.util.BioMatcherUtil; import io.mosip.authentication.common.service.util.EnvUtil; @@ -135,7 +137,8 @@ io.mosip.kernel.keymanagerservice.dto.AuthorizedRolesDTO.class, io.mosip.kernel.partnercertservice.dto.AuthorizedRolesDTO.class, io.mosip.kernel.signature.dto.AuthorizedRolesDTO.class, - EnvUtil.class, KeyBindedTokenMatcherUtil.class, HSMHealthCheck.class, PrivateKeyDecryptorHelper.class }) + EnvUtil.class, KeyBindedTokenMatcherUtil.class, HSMHealthCheck.class, PrivateKeyDecryptorHelper.class, + PasswordAuthServiceImpl.class, PasswordComparator.class }) @ComponentScan(basePackages = { "io.mosip.authentication.internal.service.*", "${mosip.auth.adapter.impl.basepackage}", "io.mosip.kernel.core.logger.config", "io.mosip.authentication.common.service.config" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = { diff --git a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalAuthTxnController.java b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalAuthTxnController.java index 1c8b844cee4..6eb73ca1b19 100644 --- a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalAuthTxnController.java +++ b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalAuthTxnController.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.Objects; import java.util.TimeZone; +import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -23,7 +24,6 @@ import org.springframework.web.bind.annotation.RestController; import io.mosip.authentication.common.service.helper.AuditHelper; -import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; import io.mosip.authentication.common.service.util.EnvUtil; import io.mosip.authentication.core.autntxn.dto.AutnTxnDto; import io.mosip.authentication.core.autntxn.dto.AutnTxnRequestDto; @@ -74,9 +74,6 @@ public class InternalAuthTxnController { @Autowired private AuditHelper auditHelper; - @Autowired - private IdAuthSecurityManager securityManager; - @InitBinder public void initBinder(WebDataBinder binder) { binder.setValidator(authTxnValidator); @@ -124,8 +121,9 @@ public ResponseEntity getAuthTxnDetails( Objects.isNull(individualIdType) ? idTypeUtil.getIdType(individualId).getType() : individualIdType); authtxnrequestdto.setPageStart(pageStart); authtxnrequestdto.setPageFetch(pageFetch); - String idvidHash = securityManager.hash(individualId); - + // Removed Storing the idvid hash value in audit entries. + // For this type of request storing a UUID instead of idvid hash. + String randomId = UUID.randomUUID().toString(); try { Errors errors = new BindException(authtxnrequestdto, "authtxnrequestdto"); authTxnValidator.validate(authtxnrequestdto, errors); @@ -137,20 +135,20 @@ public ResponseEntity getAuthTxnDetails( autnTxnResponseDto.setResponseTime(getResponseTime()); boolean status = true; - auditHelper.audit(AuditModules.AUTH_TRANSACTION_HISTORY, AuditEvents.RETRIEVE_AUTH_TRANSACTION_HISTORY_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.AUTH_TRANSACTION_HISTORY, AuditEvents.RETRIEVE_AUTH_TRANSACTION_HISTORY_REQUEST_RESPONSE, randomId, IdType.getIDTypeOrDefault(authtxnrequestdto.getIndividualIdType()), "auth transaction history status : " + status ); return new ResponseEntity<>(autnTxnResponseDto, HttpStatus.OK); } catch (IDDataValidationException e) { logger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), AUTH_TXN_DETAILS, e.getErrorText()); - auditHelper.audit(AuditModules.AUTH_TRANSACTION_HISTORY, AuditEvents.RETRIEVE_AUTH_TRANSACTION_HISTORY_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.AUTH_TRANSACTION_HISTORY, AuditEvents.RETRIEVE_AUTH_TRANSACTION_HISTORY_REQUEST_RESPONSE, randomId, IdType.getIDTypeOrDefault(authtxnrequestdto.getIndividualIdType()), e ); throw new IdAuthenticationAppException(IdAuthenticationErrorConstants.DATA_VALIDATION_FAILED, e); } catch (IdAuthenticationBusinessException e) { logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText()); - auditHelper.audit(AuditModules.AUTH_TRANSACTION_HISTORY, AuditEvents.RETRIEVE_AUTH_TRANSACTION_HISTORY_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.AUTH_TRANSACTION_HISTORY, AuditEvents.RETRIEVE_AUTH_TRANSACTION_HISTORY_REQUEST_RESPONSE, randomId, IdType.getIDTypeOrDefault(authtxnrequestdto.getIndividualIdType()), e ); throw new IdAuthenticationAppException(e.getErrorCode(), e.getErrorText(), e); } diff --git a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalOTPController.java b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalOTPController.java index f9c29fef54e..2e60506a41f 100644 --- a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalOTPController.java +++ b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalOTPController.java @@ -122,7 +122,7 @@ public OtpResponseDTO generateOTP(@Valid @RequestBody OtpRequestDTO otpRequestDt Optional partner = Optional.empty(); AuthTransactionBuilder authTxnBuilder = authTransactionHelper .createAndSetAuthTxnBuilderMetadataToRequest(otpRequestDto, !isPartnerReq, partner); - String idvidHash = securityManager.hash(otpRequestDto.getIndividualId()); + try { String idType = Objects.nonNull(otpRequestDto.getIndividualIdType()) ? otpRequestDto.getIndividualIdType() : idTypeUtil.getIdType(otpRequestDto.getIndividualId()).getType(); @@ -134,20 +134,20 @@ public OtpResponseDTO generateOTP(@Valid @RequestBody OtpRequestDTO otpRequestDt otpResponseDTO.getResponseTime()); boolean status = otpResponseDTO.getErrors() == null || otpResponseDTO.getErrors().isEmpty(); - auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.INTERNAL_OTP_TRIGGER_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.INTERNAL_OTP_TRIGGER_REQUEST_RESPONSE, otpRequestDto.getTransactionID(), IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), "Internal OTP Request status : " + status); return otpResponseDTO; } catch (IDDataValidationException e) { logger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), GENERATE_OTP, e.getErrorText()); - auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.INTERNAL_OTP_TRIGGER_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.INTERNAL_OTP_TRIGGER_REQUEST_RESPONSE, otpRequestDto.getTransactionID(), IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), e); IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWithMetadata, e); e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, otpRequestDto.getTransactionID()); throw authTransactionHelper.createDataValidationException(authTxnBuilder, e, requestWithMetadata); } catch (IdAuthenticationBusinessException e) { logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText()); - auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.INTERNAL_OTP_TRIGGER_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.INTERNAL_OTP_TRIGGER_REQUEST_RESPONSE, otpRequestDto.getTransactionID(), IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), e); authTransactionHelper.setAuthTransactionEntityMetadata(requestWithMetadata, authTxnBuilder); IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWithMetadata, e); diff --git a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalUpdateAuthTypeController.java b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalUpdateAuthTypeController.java index 0816149e4c8..4c6e23cccea 100644 --- a/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalUpdateAuthTypeController.java +++ b/authentication/authentication-internal-service/src/main/java/io/mosip/authentication/internal/service/controller/InternalUpdateAuthTypeController.java @@ -1,98 +1,98 @@ -package io.mosip.authentication.internal.service.controller; - -import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.IDA_WEBSUB_AUTHTYPE_CALLBACK_SECRET; - -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.enums.ParameterIn; -import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.authentication.common.service.helper.AuditHelper; -import io.mosip.authentication.core.constant.AuditEvents; -import io.mosip.authentication.core.constant.AuditModules; -import io.mosip.authentication.core.constant.IdAuthCommonConstants; -import io.mosip.authentication.core.exception.IDDataValidationException; -import io.mosip.authentication.core.exception.IdAuthenticationAppException; -import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; -import io.mosip.authentication.core.indauth.dto.IdType; -import io.mosip.authentication.core.logger.IdaLogger; -import io.mosip.authentication.core.spi.authtype.status.service.UpdateAuthtypeStatusService; -import io.mosip.idrepository.core.dto.AuthTypeStatusEventDTO; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.websub.model.EventModel; -import io.mosip.kernel.core.websub.spi.SubscriptionClient; -import io.mosip.kernel.websub.api.annotation.PreAuthenticateContentAndVerifyIntent; -import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; -import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; -import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; - -/** - * The InternalUpdateAuthTypeController use to fetch Auth Transaction. - * - * @author Dinesh Karuppiah.T - */ -@RestController -@Tag(name = "internal-update-auth-type-controller", description = "Internal Update Auth Type Controller") -public class InternalUpdateAuthTypeController { - - /** The logger. */ - private static Logger logger = IdaLogger.getLogger(InternalUpdateAuthTypeController.class); - - @Autowired - private UpdateAuthtypeStatusService authtypeStatusService; - - @Autowired - private AuditHelper auditHelper; - - @Autowired - private ObjectMapper mapper; - - @Autowired - @Qualifier("subscriptionExtendedClient") - SubscriptionClient subscribe; - - @PostMapping(value = "/callback/authTypeCallback/{partnerId}", consumes = "application/json") - @Operation(summary = "updateAuthtypeStatus", description = "updateAuthtypeStatus", tags = { "internal-update-auth-type-controller" }) - - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK"), - @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) - @PreAuthenticateContentAndVerifyIntent(secret = "${"+ IDA_WEBSUB_AUTHTYPE_CALLBACK_SECRET +"}", callback = "${ida-websub-auth-type-callback-relative-url}", topic = "${ida-topic-auth-type-status-updated}") - public void updateAuthtypeStatus(@RequestBody EventModel eventModel, @PathVariable("partnerId") String partnerId) - throws IdAuthenticationAppException, IDDataValidationException { - if(eventModel.getEvent() != null && eventModel.getEvent().getData() != null) { - AuthTypeStatusEventDTO event = mapper.convertValue(eventModel.getEvent().getData(), AuthTypeStatusEventDTO.class); - try { - logger.debug(IdAuthCommonConstants.SESSION_ID, "updateAuthtypeStatus", this.getClass().getCanonicalName(), "handling updateAuthtypeStatus event for partnerId: " + partnerId); - - authtypeStatusService.updateAuthTypeStatus(event.getTokenId(), event.getAuthTypeStatusList()); - - auditHelper.audit(AuditModules.AUTH_TYPE_STATUS, AuditEvents.UPDATE_AUTH_TYPE_STATUS_REQUEST_RESPONSE, - event.getTokenId(), IdType.UIN, "internal auth type status update status : " + true); - } catch (IdAuthenticationBusinessException e) { - logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText()); - auditHelper.audit(AuditModules.AUTH_TYPE_STATUS, AuditEvents.UPDATE_AUTH_TYPE_STATUS_REQUEST_RESPONSE, - event.getTokenId(), IdType.UIN, e); - throw new IdAuthenticationAppException(e.getErrorCode(), e.getErrorText(), e); - } - } - - } - -} +package io.mosip.authentication.internal.service.controller; + +import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.IDA_WEBSUB_AUTHTYPE_CALLBACK_SECRET; + +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.authentication.common.service.helper.AuditHelper; +import io.mosip.authentication.core.constant.AuditEvents; +import io.mosip.authentication.core.constant.AuditModules; +import io.mosip.authentication.core.constant.IdAuthCommonConstants; +import io.mosip.authentication.core.exception.IDDataValidationException; +import io.mosip.authentication.core.exception.IdAuthenticationAppException; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.indauth.dto.IdType; +import io.mosip.authentication.core.logger.IdaLogger; +import io.mosip.authentication.core.spi.authtype.status.service.UpdateAuthtypeStatusService; +import io.mosip.idrepository.core.dto.AuthTypeStatusEventDTO; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.websub.model.EventModel; +import io.mosip.kernel.core.websub.spi.SubscriptionClient; +import io.mosip.kernel.websub.api.annotation.PreAuthenticateContentAndVerifyIntent; +import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; +import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; +import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; + +/** + * The InternalUpdateAuthTypeController use to fetch Auth Transaction. + * + * @author Dinesh Karuppiah.T + */ +@RestController +@Tag(name = "internal-update-auth-type-controller", description = "Internal Update Auth Type Controller") +public class InternalUpdateAuthTypeController { + + /** The logger. */ + private static Logger logger = IdaLogger.getLogger(InternalUpdateAuthTypeController.class); + + @Autowired + private UpdateAuthtypeStatusService authtypeStatusService; + + @Autowired + private AuditHelper auditHelper; + + @Autowired + private ObjectMapper mapper; + + @Autowired + @Qualifier("subscriptionExtendedClient") + SubscriptionClient subscribe; + + @PostMapping(value = "/callback/authTypeCallback/{partnerId}", consumes = "application/json") + @Operation(summary = "updateAuthtypeStatus", description = "updateAuthtypeStatus", tags = { "internal-update-auth-type-controller" }) + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + @PreAuthenticateContentAndVerifyIntent(secret = "${"+ IDA_WEBSUB_AUTHTYPE_CALLBACK_SECRET +"}", callback = "${ida-websub-auth-type-callback-relative-url}", topic = "${ida-topic-auth-type-status-updated}") + public void updateAuthtypeStatus(@RequestBody EventModel eventModel, @PathVariable("partnerId") String partnerId) + throws IdAuthenticationAppException, IDDataValidationException { + if(eventModel.getEvent() != null && eventModel.getEvent().getData() != null) { + AuthTypeStatusEventDTO event = mapper.convertValue(eventModel.getEvent().getData(), AuthTypeStatusEventDTO.class); + try { + logger.debug(IdAuthCommonConstants.SESSION_ID, "updateAuthtypeStatus", this.getClass().getCanonicalName(), "handling updateAuthtypeStatus event for partnerId: " + partnerId); + + authtypeStatusService.updateAuthTypeStatus(event.getTokenId(), event.getAuthTypeStatusList()); + + auditHelper.audit(AuditModules.AUTH_TYPE_STATUS, AuditEvents.UPDATE_AUTH_TYPE_STATUS_REQUEST_RESPONSE, + eventModel.getEvent().getId(), IdType.UIN, "internal auth type status update status : " + true); + } catch (IdAuthenticationBusinessException e) { + logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText()); + auditHelper.audit(AuditModules.AUTH_TYPE_STATUS, AuditEvents.UPDATE_AUTH_TYPE_STATUS_REQUEST_RESPONSE, + eventModel.getEvent().getId(), IdType.UIN, e); + throw new IdAuthenticationAppException(e.getErrorCode(), e.getErrorText(), e); + } + } + + } + +} diff --git a/authentication/authentication-otp-service/Dockerfile b/authentication/authentication-otp-service/Dockerfile index 9228889b97c..a170041d25a 100644 --- a/authentication/authentication-otp-service/Dockerfile +++ b/authentication/authentication-otp-service/Dockerfile @@ -1,123 +1,125 @@ -FROM openjdk:11 - -ARG SOURCE -ARG COMMIT_HASH -ARG COMMIT_ID -ARG BUILD_TIME -LABEL source=${SOURCE} -LABEL commit_hash=${COMMIT_HASH} -LABEL commit_id=${COMMIT_ID} -LABEL build_time=${BUILD_TIME} - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment for hsm client zip file path -#ARG client_zip_path -ARG hsm_client_zip_path - -# can be passed during Docker build as build time environment for glowroot -ARG is_glowroot - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass glowroot, at docker runtime -ENV is_glowroot_env=${is_glowroot} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# environment variable to pass iam_adapter url, at docker runtime -ENV iam_adapter_url_env=${iam_adapter_url} - -# environment variable to pass hsm client zip file path, at docker runtime -#ENV zip_file_path=${client_zip_path} -ENV hsm_zip_file_path=${hsm_client_zip_path} - -#ENV work_dir_env=/ - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_group=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_uid=1001 - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_gid=1001 - -ARG hsm_local_dir=hsm-client - -ENV hsm_local_dir_name=${hsm_local_dir} - -# install packages and create user -RUN apt-get -y update \ -&& apt-get install -y unzip sudo \ -&& groupadd -g ${container_user_gid} ${container_user_group} \ -&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ -&& adduser ${container_user} sudo \ -&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers - -# set working directory for the user -WORKDIR /home/${container_user} - -ENV work_dir=/home/${container_user} - -ARG loader_path=${work_dir}/additional_jars - -RUN mkdir -p ${loader_path} - -ENV loader_path_env=${loader_path} - -ENV current_module_env=authentication-otp-service - -ADD configure_start.sh configure_start.sh - -RUN chmod +x configure_start.sh - -ADD target/${current_module_env}-*.jar ${current_module_env}.jar - -EXPOSE 8092 - -EXPOSE 9010 - -# change permissions of file inside working dir -RUN chown -R ${container_user}:${container_user} /home/${container_user} - -# select container user for all tasks -USER ${container_user_uid}:${container_user_gid} - -ENTRYPOINT [ "./configure_start.sh" ] - -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - sed -i "s//${current_module_env}/g" glowroot/glowroot.properties ; \ - wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Djava.security.debug=sunpkcs11 -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" ${current_module_env}.jar ; \ - else \ - wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Djava.security.debug=sunpkcs11 -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" ${current_module_env}.jar ; \ - fi - -#Sample docker run command: -# sudo docker run --rm -it -e artifactory_url_env="http://artifactory" -e spring_config_label_env="1.0.9" -e active_profile_env="dev" -e spring_config_url_env="http://config-server/config" -e PKCS11_PROXY_SOCKET=tcp://softhsm-ida:5666 -p 8092:8092 authentication-otp-service:1.0.9 \ No newline at end of file +FROM openjdk:11 + +ARG SOURCE +ARG COMMIT_HASH +ARG COMMIT_ID +ARG BUILD_TIME +LABEL source=${SOURCE} +LABEL commit_hash=${COMMIT_HASH} +LABEL commit_id=${COMMIT_ID} +LABEL build_time=${BUILD_TIME} + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG spring_config_label + +# can be passed during Docker build as build time environment for spring profiles active +ARG active_profile + +# can be passed during Docker build as build time environment for config server URL +ARG spring_config_url + +# can be passed during Docker build as build time environment for hsm client zip file path +#ARG client_zip_path +ARG hsm_client_zip_path + +# can be passed during Docker build as build time environment for glowroot +ARG is_glowroot + +# can be passed during Docker build as build time environment for artifactory URL +ARG artifactory_url + +# environment variable to pass active profile such as DEV, QA etc at docker runtime +ENV active_profile_env=${active_profile} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass spring configuration url, at docker runtime +ENV spring_config_url_env=${spring_config_url} + +# environment variable to pass glowroot, at docker runtime +ENV is_glowroot_env=${is_glowroot} + +# environment variable to pass artifactory url, at docker runtime +ENV artifactory_url_env=${artifactory_url} + +# environment variable to pass iam_adapter url, at docker runtime +ENV iam_adapter_url_env=${iam_adapter_url} + +# environment variable to pass hsm client zip file path, at docker runtime +#ENV zip_file_path=${client_zip_path} +ENV hsm_zip_file_path=${hsm_client_zip_path} + +#ENV work_dir_env=/ + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_group=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_uid=1001 + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_gid=1001 + +ARG hsm_local_dir=hsm-client + +ENV hsm_local_dir_name=${hsm_local_dir} + +# install packages and create user +RUN apt-get -y update \ +&& apt-get install -y unzip sudo \ +&& groupadd -g ${container_user_gid} ${container_user_group} \ +&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ +&& adduser ${container_user} sudo \ +&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers + +# set working directory for the user +WORKDIR /home/${container_user} + +ENV work_dir=/home/${container_user} + +ARG loader_path=${work_dir}/additional_jars + +RUN mkdir -p ${loader_path} + +ENV loader_path_env=${loader_path} + +ENV current_module_env=authentication-otp-service + +ADD configure_start.sh configure_start.sh + +ADD ./lib/* "${loader_path_env}"/ + +RUN chmod +x configure_start.sh + +ADD target/${current_module_env}-*.jar ${current_module_env}.jar + +EXPOSE 8092 + +EXPOSE 9010 + +# change permissions of file inside working dir +RUN chown -R ${container_user}:${container_user} /home/${container_user} + +# select container user for all tasks +USER ${container_user_uid}:${container_user_gid} + +ENTRYPOINT [ "./configure_start.sh" ] + +CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ + unzip glowroot.zip ; \ + rm -rf glowroot.zip ; \ + sed -i "s//${current_module_env}/g" glowroot/glowroot.properties ; \ + wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -jar -Djava.security.debug=sunpkcs11 -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" ${current_module_env}.jar ; \ + else \ + wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -jar -Djava.security.debug=sunpkcs11 -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" ${current_module_env}.jar ; \ + fi + +#Sample docker run command: +# sudo docker run --rm -it -e artifactory_url_env="http://artifactory" -e spring_config_label_env="1.0.9" -e active_profile_env="dev" -e spring_config_url_env="http://config-server/config" -e PKCS11_PROXY_SOCKET=tcp://softhsm-ida:5666 -p 8092:8092 authentication-otp-service:1.0.9 diff --git a/authentication/authentication-otp-service/lib/libargon2.so b/authentication/authentication-otp-service/lib/libargon2.so new file mode 100755 index 00000000000..bf8cad86215 Binary files /dev/null and b/authentication/authentication-otp-service/lib/libargon2.so differ diff --git a/authentication/authentication-otp-service/pom.xml b/authentication/authentication-otp-service/pom.xml index 86bd61a6818..a3e41799a59 100644 --- a/authentication/authentication-otp-service/pom.xml +++ b/authentication/authentication-otp-service/pom.xml @@ -7,9 +7,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-otp-service authentication-otp-service diff --git a/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/OtpApplication.java b/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/OtpApplication.java index 8eada82060b..15c3ffda889 100644 --- a/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/OtpApplication.java +++ b/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/OtpApplication.java @@ -30,6 +30,7 @@ import io.mosip.authentication.common.service.impl.KeyBindedTokenAuthServiceImpl; import io.mosip.authentication.common.service.impl.OTPAuthServiceImpl; import io.mosip.authentication.common.service.impl.OTPServiceImpl; +import io.mosip.authentication.common.service.impl.PasswordAuthServiceImpl; import io.mosip.authentication.common.service.impl.hotlist.HotlistServiceImpl; import io.mosip.authentication.common.service.impl.masterdata.MasterDataCacheUpdateServiceImpl; import io.mosip.authentication.common.service.impl.notification.NotificationServiceImpl; @@ -41,6 +42,7 @@ import io.mosip.authentication.common.service.integration.NotificationManager; import io.mosip.authentication.common.service.integration.OTPManager; import io.mosip.authentication.common.service.integration.PartnerServiceManager; +import io.mosip.authentication.common.service.integration.PasswordComparator; import io.mosip.authentication.common.service.integration.TokenIdManager; import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; import io.mosip.authentication.common.service.util.EnvUtil; @@ -69,7 +71,6 @@ import io.mosip.kernel.keymanager.hsm.health.HSMHealthCheck; import io.mosip.kernel.keymanager.hsm.impl.KeyStoreImpl; import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import io.mosip.kernel.keymanagerservice.helper.PrivateKeyDecryptorHelper; import io.mosip.kernel.keymanagerservice.helper.SessionKeyDecrytorHelper; import io.mosip.kernel.keymanagerservice.service.impl.KeymanagerServiceImpl; import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; @@ -81,6 +82,7 @@ import io.mosip.kernel.tokenidgenerator.generator.TokenIDGenerator; import io.mosip.kernel.tokenidgenerator.service.impl.TokenIDGeneratorServiceImpl; import io.mosip.kernel.zkcryptoservice.service.impl.ZKCryptoManagerServiceImpl; +import io.mosip.kernel.keymanagerservice.helper.PrivateKeyDecryptorHelper; /** * Spring-boot class for ID Authentication Application. @@ -108,7 +110,8 @@ LangComparatorConfig.class, OpenApiProperties.class, SessionKeyDecrytorHelper.class, ExternalRestHelperConfig.class, IdaRequestResponsConsumerUtil.class, PartnerCACertEventServiceImpl.class, PartnerCACertEventInitializer.class, IdAuthWebSubInitializer.class, AuthAnonymousEventPublisher.class, EnvUtil.class, KeyBindedTokenMatcherUtil.class, - HSMHealthCheck.class, PrivateKeyDecryptorHelper.class }) + HSMHealthCheck.class, PrivateKeyDecryptorHelper.class, + PasswordAuthServiceImpl.class, PasswordComparator.class }) @ComponentScan(basePackages = { "io.mosip.authentication.otp.service.*", "io.mosip.kernel.core.logger.config", "${mosip.auth.adapter.impl.basepackage}" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = { "io.mosip.idrepository.core.config.IdRepoDataSourceConfig.*" })) diff --git a/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/controller/OTPController.java b/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/controller/OTPController.java index a448558651a..010b1d08556 100644 --- a/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/controller/OTPController.java +++ b/authentication/authentication-otp-service/src/main/java/io/mosip/authentication/otp/service/controller/OTPController.java @@ -142,20 +142,20 @@ public OtpResponseDTO generateOTP(@Valid @RequestBody OtpRequestDTO otpRequestDt otpResponseDTO.getResponseTime()); boolean status = otpResponseDTO.getErrors() == null || otpResponseDTO.getErrors().isEmpty(); - auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE, idvidHash, + auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE, otpRequestDto.getTransactionID(), IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), "otpRequest status : " + status); return otpResponseDTO; } catch (IDDataValidationException e) { logger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), GENERATE_OTP, e.getErrorText()); - auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE , idvidHash, + auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE , otpRequestDto.getTransactionID(), IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), e); IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWithMetadata, e); e.putMetadata(IdAuthCommonConstants.TRANSACTION_ID, otpRequestDto.getTransactionID()); throw authTransactionHelper.createDataValidationException(authTxnBuilder, e, requestWithMetadata); } catch (IdAuthenticationBusinessException e) { logger.error(IdAuthCommonConstants.SESSION_ID, e.getClass().toString(), e.getErrorCode(), e.getErrorText()); - auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE , idvidHash, + auditHelper.audit(AuditModules.OTP_REQUEST, AuditEvents.OTP_TRIGGER_REQUEST_RESPONSE , otpRequestDto.getTransactionID(), IdType.getIDTypeOrDefault(otpRequestDto.getIndividualIdType()), e); authTransactionHelper.setAuthTransactionEntityMetadata(requestWithMetadata, authTxnBuilder); IdaRequestResponsConsumerUtil.setIdVersionToObjectWithMetadata(requestWithMetadata, e); diff --git a/authentication/authentication-service/Dockerfile b/authentication/authentication-service/Dockerfile index ab0a6b78234..9a884f2c320 100644 --- a/authentication/authentication-service/Dockerfile +++ b/authentication/authentication-service/Dockerfile @@ -1,145 +1,147 @@ -FROM openjdk:11 - -ARG SOURCE -ARG COMMIT_HASH -ARG COMMIT_ID -ARG BUILD_TIME -LABEL source=${SOURCE} -LABEL commit_hash=${COMMIT_HASH} -LABEL commit_id=${COMMIT_ID} -LABEL build_time=${BUILD_TIME} - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -#ARG bio_sdk_folder=mock/0.9 -ARG biosdk_zip_path - -ARG demosdk_zip_path - -# can be passed during Docker build as build time environment for hsm client zip file path -#ARG client_zip_path -ARG hsm_client_zip_path - -# can be passed during Docker build as build time environment for glowroot -ARG is_glowroot - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass glowroot, at docker runtime -ENV is_glowroot_env=${is_glowroot} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# environment variable to pass iam_adapter url, at docker runtime -ENV iam_adapter_url_env=${iam_adapter_url} - -#ENV bio_sdk_folder_env=${bio_sdk_folder} -ENV biosdk_zip_file_path=${biosdk_zip_path} - -#ENV demo_sdk_folder_env=${demo_sdk_folder} -ENV demosdk_zip_file_path=${demosdk_zip_path} - -# environment variable to pass hsm client zip file path, at docker runtime -#ENV zip_file_path=${client_zip_path} -ENV hsm_zip_file_path=${hsm_client_zip_path} - -#ENV work_dir_env=/ - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_group=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_uid=1001 - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_gid=1001 - -ARG hsm_local_dir=hsm-client - -ENV hsm_local_dir_name=${hsm_local_dir} - -ARG biosdk_local_dir=biosdk-client - -ARG demosdk_local_dir=demosdk - -ENV biosdk_local_dir_name=${biosdk_local_dir} - -ENV demosdk_local_dir_name=${demosdk_local_dir} - -# install packages and create user -RUN apt-get -y update \ -&& apt-get install -y unzip sudo \ -&& groupadd -g ${container_user_gid} ${container_user_group} \ -&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ -&& adduser ${container_user} sudo \ -&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers \ -&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${biosdk_local_dir}/install.sh" >> /etc/sudoers - -# set working directory for the user -WORKDIR /home/${container_user} - -ENV work_dir=/home/${container_user} - -ARG loader_path=${work_dir}/additional_jars/ - -RUN mkdir -p ${loader_path} - -ENV loader_path_env=${loader_path} - -ENV current_module_env=authentication-service - -ADD configure_start.sh configure_start.sh - -RUN chmod +x configure_start.sh - -ADD target/${current_module_env}-*.jar ${current_module_env}.jar - -EXPOSE 8090 - -EXPOSE 9010 - -# change permissions of file inside working dir -RUN chown -R ${container_user}:${container_user} /home/${container_user} - -# select container user for all tasks -USER ${container_user_uid}:${container_user_gid} - -ENTRYPOINT [ "./configure_start.sh" ] - -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - sed -i "s//${current_module_env}/g" glowroot/glowroot.properties ; \ - wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Djava.security.debug=sunpkcs11 -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ - else \ - wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ - wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Djava.security.debug=sunpkcs11 -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ - fi - -#Sample docker run command: -# sudo docker run --rm -it -e artifactory_url_env="http://artifactory" -e spring_config_label_env="1.0.9" -e active_profile_env="dev" -e spring_config_url_env="http://config-server/config" -e PKCS11_PROXY_SOCKET=tcp://softhsm-ida:5666 -p 8090:8090 authentication-service:1.0.9 \ No newline at end of file +FROM openjdk:11 + +ARG SOURCE +ARG COMMIT_HASH +ARG COMMIT_ID +ARG BUILD_TIME +LABEL source=${SOURCE} +LABEL commit_hash=${COMMIT_HASH} +LABEL commit_id=${COMMIT_ID} +LABEL build_time=${BUILD_TIME} + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG spring_config_label + +# can be passed during Docker build as build time environment for spring profiles active +ARG active_profile + +# can be passed during Docker build as build time environment for config server URL +ARG spring_config_url + +#ARG bio_sdk_folder=mock/0.9 +ARG biosdk_zip_path + +ARG demosdk_zip_path + +# can be passed during Docker build as build time environment for hsm client zip file path +#ARG client_zip_path +ARG hsm_client_zip_path + +# can be passed during Docker build as build time environment for glowroot +ARG is_glowroot + +# can be passed during Docker build as build time environment for artifactory URL +ARG artifactory_url + +# environment variable to pass active profile such as DEV, QA etc at docker runtime +ENV active_profile_env=${active_profile} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass spring configuration url, at docker runtime +ENV spring_config_url_env=${spring_config_url} + +# environment variable to pass glowroot, at docker runtime +ENV is_glowroot_env=${is_glowroot} + +# environment variable to pass artifactory url, at docker runtime +ENV artifactory_url_env=${artifactory_url} + +# environment variable to pass iam_adapter url, at docker runtime +ENV iam_adapter_url_env=${iam_adapter_url} + +#ENV bio_sdk_folder_env=${bio_sdk_folder} +ENV biosdk_zip_file_path=${biosdk_zip_path} + +#ENV demo_sdk_folder_env=${demo_sdk_folder} +ENV demosdk_zip_file_path=${demosdk_zip_path} + +# environment variable to pass hsm client zip file path, at docker runtime +#ENV zip_file_path=${client_zip_path} +ENV hsm_zip_file_path=${hsm_client_zip_path} + +#ENV work_dir_env=/ + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_group=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_uid=1001 + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_gid=1001 + +ARG hsm_local_dir=hsm-client + +ENV hsm_local_dir_name=${hsm_local_dir} + +ARG biosdk_local_dir=biosdk-client + +ARG demosdk_local_dir=demosdk + +ENV biosdk_local_dir_name=${biosdk_local_dir} + +ENV demosdk_local_dir_name=${demosdk_local_dir} + +# install packages and create user +RUN apt-get -y update \ +&& apt-get install -y unzip sudo \ +&& groupadd -g ${container_user_gid} ${container_user_group} \ +&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ +&& adduser ${container_user} sudo \ +&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers \ +&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${biosdk_local_dir}/install.sh" >> /etc/sudoers + +# set working directory for the user +WORKDIR /home/${container_user} + +ENV work_dir=/home/${container_user} + +ARG loader_path=${work_dir}/additional_jars/ + +RUN mkdir -p ${loader_path} + +ENV loader_path_env=${loader_path} + +ENV current_module_env=authentication-service + +ADD configure_start.sh configure_start.sh + +ADD ./lib/* "${loader_path_env}"/ + +RUN chmod +x configure_start.sh + +ADD target/${current_module_env}-*.jar ${current_module_env}.jar + +EXPOSE 8090 + +EXPOSE 9010 + +# change permissions of file inside working dir +RUN chown -R ${container_user}:${container_user} /home/${container_user} + +# select container user for all tasks +USER ${container_user_uid}:${container_user_gid} + +ENTRYPOINT [ "./configure_start.sh" ] + +CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ + unzip glowroot.zip ; \ + rm -rf glowroot.zip ; \ + sed -i "s//${current_module_env}/g" glowroot/glowroot.properties ; \ + wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -jar -Djava.security.debug=sunpkcs11 -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ + else \ + wget -q "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/authentication/authentication-ref-impl/authentication-childauthfilter-impl.jar -O "${loader_path_env}"/authentication-childauthfilter-impl.jar ; \ + wget -q "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -jar -Djava.security.debug=sunpkcs11 -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dloader.path="${loader_path_env}" -Dfile.encoding="UTF-8" ${current_module_env}.jar ; \ + fi + +#Sample docker run command: +# sudo docker run --rm -it -e artifactory_url_env="http://artifactory" -e spring_config_label_env="1.0.9" -e active_profile_env="dev" -e spring_config_url_env="http://config-server/config" -e PKCS11_PROXY_SOCKET=tcp://softhsm-ida:5666 -p 8090:8090 authentication-service:1.0.9 diff --git a/authentication/authentication-service/lib/libargon2.so b/authentication/authentication-service/lib/libargon2.so new file mode 100755 index 00000000000..bf8cad86215 Binary files /dev/null and b/authentication/authentication-service/lib/libargon2.so differ diff --git a/authentication/authentication-service/pom.xml b/authentication/authentication-service/pom.xml index 47d388b97a0..b0bda69ffee 100644 --- a/authentication/authentication-service/pom.xml +++ b/authentication/authentication-service/pom.xml @@ -6,9 +6,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT authentication-service jar diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/IdAuthenticationApplication.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/IdAuthenticationApplication.java index 1f54f60bdec..53acc55a0f8 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/IdAuthenticationApplication.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/IdAuthenticationApplication.java @@ -33,6 +33,7 @@ import io.mosip.authentication.common.service.impl.IdInfoFetcherImpl; import io.mosip.authentication.common.service.impl.IdServiceImpl; import io.mosip.authentication.common.service.impl.OTPAuthServiceImpl; +import io.mosip.authentication.common.service.impl.PasswordAuthServiceImpl; import io.mosip.authentication.common.service.impl.KeyBindedTokenAuthServiceImpl; import io.mosip.authentication.common.service.impl.hotlist.HotlistServiceImpl; import io.mosip.authentication.common.service.impl.masterdata.MasterDataCacheUpdateServiceImpl; @@ -45,6 +46,7 @@ import io.mosip.authentication.common.service.integration.NotificationManager; import io.mosip.authentication.common.service.integration.OTPManager; import io.mosip.authentication.common.service.integration.PartnerServiceManager; +import io.mosip.authentication.common.service.integration.PasswordComparator; import io.mosip.authentication.common.service.integration.TokenIdManager; import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; import io.mosip.authentication.common.service.util.BioMatcherUtil; @@ -92,7 +94,7 @@ import io.mosip.kernel.tokenidgenerator.service.impl.TokenIDGeneratorServiceImpl; import io.mosip.kernel.zkcryptoservice.service.impl.ZKCryptoManagerServiceImpl; import io.mosip.kernel.keymanager.hsm.health.HSMHealthCheck; - +import io.mosip.kernel.keymanagerservice.helper.PrivateKeyDecryptorHelper; /** * Spring-boot class for ID Authentication Application. @@ -102,7 +104,7 @@ */ @SpringBootApplication(exclude = { HibernateDaoConfig.class, SecurityAutoConfiguration.class }) @Import(value = { IdValidationUtil.class, IDAMappingConfig.class, KeyBindedTokenAuthServiceImpl.class, - AuthContextClazzRefProvider.class, CbeffImpl.class, + AuthContextClazzRefProvider.class, CbeffImpl.class, RestRequestFactory.class, AuditRequestFactory.class, AuditRequestFactory.class, NotificationManager.class, NotificationServiceImpl.class, IdTemplateManager.class, TemplateManagerBuilderImpl.class, IdAuthExceptionHandler.class, IdInfoFetcherImpl.class, OTPManager.class, MasterDataManager.class, IdInfoHelper.class, OTPAuthServiceImpl.class, @@ -122,7 +124,8 @@ IdAuthFraudAnalysisEventManager.class, IdAuthFraudAnalysisEventPublisher.class, AuthFiltersValidator.class, AuthAnonymousProfileServiceImpl.class, AuthAnonymousEventPublisher.class, SessionKeyDecrytorHelper.class, ExternalRestHelperConfig.class, IdaRequestResponsConsumerUtil.class, PartnerCACertEventServiceImpl.class, PartnerCACertEventInitializer.class, EnvUtil.class, KeyBindedTokenMatcherUtil.class, - HSMHealthCheck.class, TokenValidationHelper.class, VCSchemaProviderUtil.class, PrivateKeyDecryptorHelper.class }) + HSMHealthCheck.class, TokenValidationHelper.class, VCSchemaProviderUtil.class, PrivateKeyDecryptorHelper.class, + PasswordAuthServiceImpl.class, PasswordComparator.class }) @ComponentScan(basePackages = { "io.mosip.authentication.service.*", "io.mosip.kernel.core.logger.config", "io.mosip.authentication.common.service.config", "${mosip.auth.adapter.impl.basepackage}" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = { "io.mosip.idrepository.core.config.IdRepoDataSourceConfig.*" })) diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/controller/VCIController.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/controller/VCIController.java index 249194edb04..1bf86e24cd3 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/controller/VCIController.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/controller/VCIController.java @@ -162,4 +162,4 @@ public VciExchangeResponseDTO vciExchange(@Validated @RequestBody VciExchangeReq throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.UNABLE_TO_PROCESS); } } -} \ No newline at end of file +} diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/IdentityKeyBindingFacadeImpl.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/IdentityKeyBindingFacadeImpl.java index 8b50c452e74..37b60e3cb82 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/IdentityKeyBindingFacadeImpl.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/IdentityKeyBindingFacadeImpl.java @@ -146,14 +146,14 @@ public IdentityKeyBindingResponseDto processIdentityKeyBinding(@NotNull Identity status = keyBindingResponseEntry.getValue(); saveToTxnTable(identityKeyBindingRequestDTO, status, partnerId, token, authResponseDTO, keyBindingResponseDto, metadata); auditHelper.audit(AuditModules.IDENTITY_KEY_BINDING, AuditEvents.KEY_BINDIN_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(identityKeyBindingRequestDTO.getIndividualIdType()), + identityKeyBindingRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(identityKeyBindingRequestDTO.getIndividualIdType()), "Identity Key Binding status : " + status); return keyBindingResponseDto; } catch (IdAuthenticationBusinessException e) { status = false; saveToTxnTable(identityKeyBindingRequestDTO, status, partnerId, token, authResponseDTO, keyBindingResponseDto, metadata); auditHelper.audit(AuditModules.IDENTITY_KEY_BINDING, AuditEvents.KEY_BINDIN_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(identityKeyBindingRequestDTO.getIndividualIdType()), e); + identityKeyBindingRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(identityKeyBindingRequestDTO.getIndividualIdType()), e); throw e; } } diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/KycFacadeImpl.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/KycFacadeImpl.java index a181c6a7cd9..c8c5c8db3c1 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/KycFacadeImpl.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/KycFacadeImpl.java @@ -197,14 +197,14 @@ public EKycAuthResponseDTO processEKycAuth(@Nonnull EkycAuthRequestDTO kycAuthRe status = kycAuthResponse.getValue(); saveToTxnTable(kycAuthRequestDTO, status, partnerId, token, authResponseDTO, kycAuthResponseDTO, metadata, false); auditHelper.audit(AuditModules.EKYC_AUTH, AuditEvents.EKYC_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), - "kycAuthentication status : " + status); + kycAuthRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), + "kycAuthentication status : " + status); return kycAuthResponseDTO; } catch (IdAuthenticationBusinessException e) { status = false; saveToTxnTable(kycAuthRequestDTO, status, partnerId, token, authResponseDTO, kycAuthResponseDTO, metadata, false); auditHelper.audit(AuditModules.EKYC_AUTH, AuditEvents.EKYC_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), e); + kycAuthRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), e); throw e; } } @@ -330,14 +330,14 @@ public KycAuthResponseDTO processKycAuth(@Nonnull AuthRequestDTO kycAuthRequestD status = kycAuthResponse.getValue(); saveToTxnTable(kycAuthRequestDTO, status, partnerId, token, authResponseDTO, kycAuthResponseDTO, metadata, true); auditHelper.audit(AuditModules.KYC_AUTH, AuditEvents.KYC_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), + kycAuthRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), "kycAuthentication status : " + status); return kycAuthResponseDTO; } catch (IdAuthenticationBusinessException e) { status = false; saveToTxnTable(kycAuthRequestDTO, status, partnerId, token, authResponseDTO, kycAuthResponseDTO, metadata, true); auditHelper.audit(AuditModules.KYC_AUTH, AuditEvents.KYC_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), e); + kycAuthRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(kycAuthRequestDTO.getIndividualIdType()), e); throw e; } } @@ -452,16 +452,17 @@ public KycExchangeResponseDTO processKycExchange(KycExchangeRequestDTO kycExchan kycExchangeResponseDTO.setResponse(encryptedKycRespDTO); saveToTxnTable(kycExchangeRequestDTO, false, true, partnerId, token, kycExchangeResponseDTO, requestWithMetadata); auditHelper.audit(AuditModules.KYC_EXCHANGE, AuditEvents.KYC_EXCHANGE_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(kycExchangeRequestDTO.getIndividualIdType()), + kycExchangeRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(kycExchangeRequestDTO.getIndividualIdType()), IdAuthCommonConstants.KYC_EXCHANGE_SUCCESS); return kycExchangeResponseDTO; } catch(IdAuthenticationBusinessException e) { auditHelper.audit(AuditModules.KYC_EXCHANGE, AuditEvents.KYC_EXCHANGE_REQUEST_RESPONSE, - idHash, IdType.getIDTypeOrDefault(kycExchangeRequestDTO.getIndividualIdType()), e); + kycExchangeRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(kycExchangeRequestDTO.getIndividualIdType()), e); throw e; } } + // Need to move below duplicate code to common to be used by OTPService and KycExchange. private void saveToTxnTable(KycExchangeRequestDTO kycExchangeRequestDTO, boolean isInternal, boolean status, String partnerId, String token, KycExchangeResponseDTO kycExchangeResponseDTO, ObjectWithMetadata requestWithMetadata) diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/VciFacadeImpl.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/VciFacadeImpl.java index 86d104ca8d0..14e836410e6 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/VciFacadeImpl.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/facade/VciFacadeImpl.java @@ -1,3 +1,6 @@ +/** + * + */ package io.mosip.authentication.service.kyc.facade; import java.util.ArrayList; @@ -57,7 +60,7 @@ * * Facade to Verifiable Credential details * - * @author Dinesh Karuppiah.T + * @author Mahammed Taheer */ @Component public class VciFacadeImpl implements VciFacade { @@ -183,12 +186,12 @@ public VciExchangeResponseDTO processVciExchange(VciExchangeRequestDTO vciExchan vciExchangeResponseDTO.setResponse(vcResponseDTO); saveToTxnTable(vciExchangeRequestDTO, false, true, partnerId, token, vciExchangeResponseDTO, requestWithMetadata); auditHelper.audit(AuditModules.VCI_EXCHANGE, AuditEvents.VCI_EXCHANGE_REQUEST_RESPONSE, - idvidHash, IdType.getIDTypeOrDefault(vciExchangeRequestDTO.getIndividualIdType()), + vciExchangeRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(vciExchangeRequestDTO.getIndividualIdType()), IdAuthCommonConstants.VCI_EXCHANGE_SUCCESS); return vciExchangeResponseDTO; } catch(IdAuthenticationBusinessException e) { auditHelper.audit(AuditModules.VCI_EXCHANGE, AuditEvents.VCI_EXCHANGE_REQUEST_RESPONSE, - idvidHash, IdType.getIDTypeOrDefault(vciExchangeRequestDTO.getIndividualIdType()), e); + vciExchangeRequestDTO.getTransactionID(), IdType.getIDTypeOrDefault(vciExchangeRequestDTO.getIndividualIdType()), e); throw e; } } diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/filter/KycAuthFilter.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/filter/KycAuthFilter.java index de11d4f2ebc..426f3824b39 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/filter/KycAuthFilter.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/filter/KycAuthFilter.java @@ -59,6 +59,8 @@ protected void checkAllowedAuthTypeBasedOnPolicy(Map requestBody if (AuthTypeUtil.isKeyBindedToken(kycAuthRequestDTO)) { super.checkAllowedAuthTypeForKeyBindedToken(requestBody, authPolicies); } + + super.checkAllowedAuthTypeForPassword(requestBody, authPolicies); } catch (IOException e) { throw new IdAuthenticationAppException(IdAuthenticationErrorConstants.UNABLE_TO_PROCESS, e); } diff --git a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/util/ExchangeDataAttributesUtil.java b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/util/ExchangeDataAttributesUtil.java index 9df519391df..477ce9b5568 100644 --- a/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/util/ExchangeDataAttributesUtil.java +++ b/authentication/authentication-service/src/main/java/io/mosip/authentication/service/kyc/util/ExchangeDataAttributesUtil.java @@ -5,6 +5,7 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -76,10 +77,9 @@ public List filterAllowedUserClaims(String oidcClientId, List co return List.of(); } - List oidcClientAllowedUserClaims = List.of(oidcClientData.get().getUserClaims()) - .stream() - .map(String::toLowerCase) - .collect(Collectors.toList()); + List oidcClientAllowedUserClaims = Stream.of(oidcClientData.get().getUserClaims()) + .collect(Collectors.toList()); + if (consentAttributes.isEmpty()) { return oidcClientAllowedUserClaims; } diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/KycFacadeImplTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/KycFacadeImplTest.java index 9262bbd7fbf..fea03013825 100644 --- a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/KycFacadeImplTest.java +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/KycFacadeImplTest.java @@ -311,6 +311,7 @@ private String signJwt(String individualId, X509Certificate certificate, boolean } @Test + @Ignore public void authenticateIndividualTest() throws IdAuthenticationBusinessException, IdAuthenticationDaoException, Exception { String partnerData = "{\"policyId\":\"21\",\"policyName\":\"policy 1635497343191\",\"policyDescription\":\"Auth Policy\",\"policyStatus\":true,\"partnerId\":\"1635497344579\",\"partnerName\":\"1635497344579\",\"certificateData\":\"data\",\"policyExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"apiKeyExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"mispExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"policy\":{\"allowedAuthTypes\":[{\"authType\":\"otp\",\"authSubType\":\"\",\"mandatory\":true},{\"authType\":\"demo\",\"authSubType\":\"\",\"mandatory\":false},{\"authType\":\"bio\",\"authSubType\":\"FINGER\",\"mandatory\":true},{\"authType\":\"bio\",\"authSubType\":\"IRIS\",\"mandatory\":false},{\"authType\":\"bio\",\"authSubType\":\"FACE\",\"mandatory\":false},{\"authType\":\"kyc\",\"authSubType\":\"\",\"mandatory\":false}],\"allowedKycAttributes\":[{\"attributeName\":\"fullName\",\"required\":true},{\"attributeName\":\"dateOfBirth\",\"required\":true},{\"attributeName\":\"gender\",\"required\":true},{\"attributeName\":\"phone\",\"required\":true},{\"attributeName\":\"email\",\"required\":true},{\"attributeName\":\"addressLine1\",\"required\":true},{\"attributeName\":\"addressLine2\",\"required\":true},{\"attributeName\":\"addressLine3\",\"required\":true},{\"attributeName\":\"location1\",\"required\":true},{\"attributeName\":\"location2\",\"required\":true},{\"attributeName\":\"location3\",\"required\":true},{\"attributeName\":\"postalCode\",\"required\":false},{\"attributeName\":\"photo\",\"required\":true}],\"authTokenType\":\"Partner\"}}"; PartnerPolicyResponseDTO partnerPolicyResponseDTO = mapper.readValue(partnerData, PartnerPolicyResponseDTO.class); @@ -413,6 +414,7 @@ public void authenticateIndividualTest() throws IdAuthenticationBusinessExceptio } @Test + @Ignore public void authenticateIndividualTest_kycAttribHasPhoto() throws IdAuthenticationBusinessException, IdAuthenticationDaoException, Exception { String partnerData = "{\"policyId\":\"21\",\"policyName\":\"policy 1635497343191\",\"policyDescription\":\"Auth Policy\",\"policyStatus\":true,\"partnerId\":\"1635497344579\",\"partnerName\":\"1635497344579\",\"certificateData\":\"data\",\"policyExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"apiKeyExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"mispExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"policy\":{\"allowedAuthTypes\":[{\"authType\":\"otp\",\"authSubType\":\"\",\"mandatory\":true},{\"authType\":\"demo\",\"authSubType\":\"\",\"mandatory\":false},{\"authType\":\"bio\",\"authSubType\":\"FINGER\",\"mandatory\":true},{\"authType\":\"bio\",\"authSubType\":\"IRIS\",\"mandatory\":false},{\"authType\":\"bio\",\"authSubType\":\"FACE\",\"mandatory\":false},{\"authType\":\"kyc\",\"authSubType\":\"\",\"mandatory\":false}],\"allowedKycAttributes\":[{\"attributeName\":\"fullName\",\"required\":true},{\"attributeName\":\"dateOfBirth\",\"required\":true},{\"attributeName\":\"gender\",\"required\":true},{\"attributeName\":\"phone\",\"required\":true},{\"attributeName\":\"email\",\"required\":true},{\"attributeName\":\"addressLine1\",\"required\":true},{\"attributeName\":\"addressLine2\",\"required\":true},{\"attributeName\":\"addressLine3\",\"required\":true},{\"attributeName\":\"location1\",\"required\":true},{\"attributeName\":\"location2\",\"required\":true},{\"attributeName\":\"location3\",\"required\":true},{\"attributeName\":\"postalCode\",\"required\":false},{\"attributeName\":\"photo\",\"required\":true}],\"authTokenType\":\"Partner\"}}"; PartnerPolicyResponseDTO partnerPolicyResponseDTO = mapper.readValue(partnerData, PartnerPolicyResponseDTO.class); @@ -515,6 +517,7 @@ public void authenticateIndividualTest_kycAttribHasPhoto() throws IdAuthenticati } @Test + @Ignore public void kycAuthenticateIndividualTest() throws IdAuthenticationBusinessException, IdAuthenticationDaoException, Exception { String partnerData = "{\"policyId\":\"21\",\"policyName\":\"policy 1635497343191\",\"policyDescription\":\"Auth Policy\",\"policyStatus\":true,\"partnerId\":\"1635497344579\",\"partnerName\":\"1635497344579\",\"certificateData\":\"data\",\"policyExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"apiKeyExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"mispExpiresOn\":\"2022-12-11T06:12:52.994Z\",\"policy\":{\"allowedAuthTypes\":[{\"authType\":\"otp\",\"authSubType\":\"\",\"mandatory\":true},{\"authType\":\"demo\",\"authSubType\":\"\",\"mandatory\":false},{\"authType\":\"bio\",\"authSubType\":\"FINGER\",\"mandatory\":true},{\"authType\":\"bio\",\"authSubType\":\"IRIS\",\"mandatory\":false},{\"authType\":\"bio\",\"authSubType\":\"FACE\",\"mandatory\":false},{\"authType\":\"kyc\",\"authSubType\":\"\",\"mandatory\":false}],\"allowedKycAttributes\":[{\"attributeName\":\"fullName\",\"required\":true},{\"attributeName\":\"dateOfBirth\",\"required\":true},{\"attributeName\":\"gender\",\"required\":true},{\"attributeName\":\"phone\",\"required\":true},{\"attributeName\":\"email\",\"required\":true},{\"attributeName\":\"addressLine1\",\"required\":true},{\"attributeName\":\"addressLine2\",\"required\":true},{\"attributeName\":\"addressLine3\",\"required\":true},{\"attributeName\":\"location1\",\"required\":true},{\"attributeName\":\"location2\",\"required\":true},{\"attributeName\":\"location3\",\"required\":true},{\"attributeName\":\"postalCode\",\"required\":false},{\"attributeName\":\"photo\",\"required\":true}],\"authTokenType\":\"Partner\"}}"; PartnerPolicyResponseDTO partnerPolicyResponseDTO = mapper.readValue(partnerData, PartnerPolicyResponseDTO.class); @@ -618,6 +621,7 @@ public void kycAuthenticateIndividualTest() throws IdAuthenticationBusinessExcep @Test + @Ignore public void processKycAuthValid() throws IdAuthenticationBusinessException, JsonProcessingException { Map mapData = new HashMap<>(); mapData.put("uin", "863537"); @@ -713,6 +717,7 @@ public void processKycAuthValid() throws IdAuthenticationBusinessException, Json } @Test + @Ignore public void processKycAuth_EncryptionException() throws IdAuthenticationBusinessException, JsonProcessingException { Map mapData = new HashMap<>(); mapData.put("uin", "863537"); @@ -813,6 +818,7 @@ public void processKycAuth_EncryptionException() throws IdAuthenticationBusiness } @Test(expected = IdAuthenticationBusinessException.class) + @Ignore public void processKycAuthException1() throws IdAuthenticationBusinessException, JsonProcessingException { EkycAuthRequestDTO kycAuthRequestDTO = new EkycAuthRequestDTO(); Map kycReqMetadata = new HashMap<>(); diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/VciFacadeImplTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/VciFacadeImplTest.java new file mode 100644 index 00000000000..835294d8bec --- /dev/null +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/facade/VciFacadeImplTest.java @@ -0,0 +1,179 @@ +package io.mosip.authentication.service.kyc.facade; + + + +import io.mosip.authentication.common.manager.IdAuthFraudAnalysisEventManager; +import io.mosip.authentication.common.service.entity.AutnTxn; +import io.mosip.authentication.common.service.entity.KycTokenData; +import io.mosip.authentication.common.service.helper.AuditHelper; +import io.mosip.authentication.common.service.helper.TokenValidationHelper; +import io.mosip.authentication.common.service.integration.TokenIdManager; +import io.mosip.authentication.common.service.repository.IdaUinHashSaltRepo; +import io.mosip.authentication.common.service.repository.KycTokenDataRepository; +import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; +import io.mosip.authentication.common.service.util.EnvUtil; +import io.mosip.authentication.common.service.util.TestObjectWithMetadata; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.indauth.dto.VciCredentialsDefinitionRequestDTO; +import io.mosip.authentication.core.indauth.dto.VciExchangeRequestDTO; +import io.mosip.authentication.core.partner.dto.*; +import io.mosip.authentication.core.spi.id.service.IdService; +import io.mosip.authentication.core.spi.partner.service.PartnerService; +import io.mosip.authentication.service.kyc.impl.VciServiceImpl; +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.*; + +@RunWith(SpringRunner.class) +@Import(EnvUtil.class) +public class VciFacadeImplTest { + + @Autowired + EnvUtil env; + + @Mock + EnvUtil envMock; + + @Mock + IdService idService; + + /** The AuditHelper */ + @Mock + AuditHelper auditHelper; + + @Mock + IdaUinHashSaltRepo uinHashSaltRepo; + + @Mock + TokenIdManager tokenIdManager; + + @Mock + IdAuthSecurityManager securityManager; + + @Mock + PartnerService partnerService; + + @Mock + IdAuthFraudAnalysisEventManager fraudEventManager; + + @Mock + VciServiceImpl vciServiceImpl; + + @Mock + TokenValidationHelper tokenValidationHelper; + + @Mock + KycTokenDataRepository kycTokenDataRepo; + + @InjectMocks + VciFacadeImpl vciFacadeImpl; + + @Test + public void processVciExchangeTestWithInvalidDetails_ThenFail() throws IdAuthenticationBusinessException { + + VciExchangeRequestDTO vciExchangeRequestDTO = new VciExchangeRequestDTO(); + vciExchangeRequestDTO.setId("12345678901234567890123456789012"); + vciExchangeRequestDTO.setMetadata(new HashMap<>()) ; + vciExchangeRequestDTO.setRequestTime("2019-07-15T12:00:00.000Z"); + vciExchangeRequestDTO.setVcAuthToken("12345678901234567890123456789012"); + vciExchangeRequestDTO.setCredSubjectId("12345678901234567890123456789012"); + vciExchangeRequestDTO.setVcFormat("WLA"); + vciExchangeRequestDTO.setIndividualId("1234567890"); + vciExchangeRequestDTO.setIndividualIdType("UIN"); + + VciCredentialsDefinitionRequestDTO vciCredentialsDefinitionRequestDTO = new VciCredentialsDefinitionRequestDTO(); + vciCredentialsDefinitionRequestDTO.setContext(List.of("https://www.w3.org/2018/credentials/v1")); + vciCredentialsDefinitionRequestDTO.setType(List.of("VerifiableCredential")); + vciCredentialsDefinitionRequestDTO.setCredentialSubject(new HashMap<>()); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + + Map metaData=new HashMap<>(); + + try{ + vciFacadeImpl.processVciExchange(vciExchangeRequestDTO,"1234567890","12345",metaData,new TestObjectWithMetadata()); + }catch(IdAuthenticationBusinessException e){ + Assert.assertEquals("IDA-KYE-006",e.getErrorCode()); + } + } + + @Test + public void processVciExchangeTestWithInValidTxnDetails_ThenFail() throws IdAuthenticationBusinessException { + ReflectionTestUtils.setField(vciFacadeImpl, "tokenValidationHelper", tokenValidationHelper); + + VciExchangeRequestDTO vciExchangeRequestDTO = new VciExchangeRequestDTO(); + vciExchangeRequestDTO.setId("12345678901234567890123456789012"); + vciExchangeRequestDTO.setMetadata(new HashMap<>()) ; + vciExchangeRequestDTO.setRequestTime("2019-07-15T12:00:00.000Z"); + vciExchangeRequestDTO.setVcAuthToken("12345678901234567890123456789012"); + vciExchangeRequestDTO.setCredSubjectId("12345678901234567890123456789012"); + vciExchangeRequestDTO.setVcFormat("WLA"); + vciExchangeRequestDTO.setIndividualId("1234567890"); + vciExchangeRequestDTO.setIndividualIdType("UIN"); + vciExchangeRequestDTO.setTransactionID("12345"); + + VciCredentialsDefinitionRequestDTO vciCredentialsDefinitionRequestDTO = new VciCredentialsDefinitionRequestDTO(); + vciCredentialsDefinitionRequestDTO.setContext(List.of("https://www.w3.org/2018/credentials/v1")); + vciCredentialsDefinitionRequestDTO.setType(List.of("VerifiableCredential")); + vciCredentialsDefinitionRequestDTO.setCredentialSubject(new HashMap<>()); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + + Map metaData=new HashMap<>(); + + PartnerPolicyResponseDTO partnerPolicyResponseDTO = new PartnerPolicyResponseDTO(); + partnerPolicyResponseDTO.setMispPolicyId("1234567890"); + + MispPolicyDTO mispPolicyDTO = new MispPolicyDTO(); + mispPolicyDTO.setAllowKeyBindingDelegation(true); + mispPolicyDTO.setAllowKycRequestDelegation(true); + mispPolicyDTO.setAllowOTPRequestDelegation(true); + + PolicyDTO policyDTO = new PolicyDTO(); + + List listOfPolicy=new ArrayList<>(); + + AuthPolicy authPolicy=new AuthPolicy(); + authPolicy.setAuthType("OTP"); + authPolicy.setAuthSubType("OTP"); + authPolicy.setMandatory(false); + + listOfPolicy.add(authPolicy); + + policyDTO.setAllowedAuthTypes(listOfPolicy); + policyDTO.setAuthTokenType("OTP"); + + partnerPolicyResponseDTO.setPolicy(policyDTO); + partnerPolicyResponseDTO.setMispPolicy(mispPolicyDTO); + partnerPolicyResponseDTO.setPartnerId("1234567890"); + + KycTokenData kycTokenData = new KycTokenData(); + kycTokenData.setPsuToken("1234567890"); + + Mockito.when(securityManager.hash(Mockito.anyString())).thenReturn("1234567890"); + Mockito.when(tokenValidationHelper.findAndValidateIssuedToken("12345678901234567890123456789012","12345","12345","1234567890")).thenReturn(kycTokenData); + Mockito.when(partnerService.getPolicyForPartner(Mockito.anyString(),Mockito.anyString(),Mockito.anyMap())).thenReturn(Optional.of(partnerPolicyResponseDTO)); + Mockito.when(idService.getToken(Mockito.any())).thenReturn("token"); + Mockito.when(tokenIdManager.generateTokenId(Mockito.anyString(),Mockito.anyString())).thenReturn("1234567890"); + + EnvUtil.setAuthTokenRequired(true); + PartnerDTO partnerDTO= new PartnerDTO(); + partnerDTO.setPartnerId("12345"); + partnerDTO.setPartnerName("relyingPartyId"); + Mockito.when(partnerService.getPartner(Mockito.anyString(),Mockito.anyMap())).thenReturn(Optional.of(partnerDTO)); + try{ + vciFacadeImpl.processVciExchange(vciExchangeRequestDTO,"1234567890","12345",metaData,new TestObjectWithMetadata()); + }catch (Exception e){ + } + + } +} diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/filter/KycAuthFilterTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/filter/KycAuthFilterTest.java new file mode 100644 index 00000000000..8047c54161c --- /dev/null +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/filter/KycAuthFilterTest.java @@ -0,0 +1,58 @@ +package io.mosip.authentication.service.kyc.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.authentication.common.service.util.EnvUtil; +import io.mosip.authentication.core.exception.IdAuthenticationAppException; +import io.mosip.authentication.core.partner.dto.AuthPolicy; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.context.WebApplicationContext; + +import java.lang.reflect.UndeclaredThrowableException; +import java.util.Collections; +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@WebMvcTest +@ContextConfiguration(classes = { TestContext.class, WebApplicationContext.class }) +@Import(EnvUtil.class) +public class KycAuthFilterTest { + @Autowired + EnvUtil env; + KycAuthFilter kyAuthFilter = new KycAuthFilter(); + @Autowired + ObjectMapper mapper; + + @Before + public void before() { + ReflectionTestUtils.setField(kyAuthFilter, "mapper", mapper); + ReflectionTestUtils.setField(kyAuthFilter, "env", env); + } + @Test + public void checkAllowedAuthTypeBasedOnPolicyTest() { + AuthPolicy authPolicy = new AuthPolicy(); + authPolicy.setAuthType("demo"); + authPolicy.setMandatory(true); + try { + ReflectionTestUtils.invokeMethod(kyAuthFilter, "checkAllowedAuthTypeBasedOnPolicy", new HashMap<>(), Collections.singletonList(authPolicy)); + } catch (UndeclaredThrowableException e) { + String detailMessage = e.getUndeclaredThrowable().getMessage(); + String[] error = detailMessage.split("-->"); + assertEquals("IDA-MPA-025", error[0].trim()); + assertEquals("Partner is unauthorised for KYC-Auth", error[1].trim()); + assertTrue(e.getCause().getClass().equals(IdAuthenticationAppException.class)); + } + } + +} diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/filter/KycExchangeFilterTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/filter/KycExchangeFilterTest.java new file mode 100644 index 00000000000..ec668900b72 --- /dev/null +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/filter/KycExchangeFilterTest.java @@ -0,0 +1,68 @@ +package io.mosip.authentication.service.kyc.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.authentication.common.service.util.EnvUtil; +import io.mosip.authentication.core.exception.IdAuthenticationAppException; +import io.mosip.authentication.core.partner.dto.AuthPolicy; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.context.WebApplicationContext; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.Collections; +import java.util.HashMap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +@RunWith(SpringRunner.class) +@WebMvcTest +@ContextConfiguration(classes = { TestContext.class, WebApplicationContext.class }) +@Import(EnvUtil.class) +public class KycExchangeFilterTest { + @Autowired + EnvUtil env; + KycExchangeFilter kycExchangeFilter = new KycExchangeFilter(); + @Autowired + ObjectMapper mapper; + + byte[] key = {48, -126, 1, 34, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -126, 1, 15, 0, 48, + -126, 1, 10, 2, -126, 1, 1, 0, -56, 41, -49, 92, 30, -78, 87, 22, -103, -23, -14, 106, -89, 84, -73, 51, + -69, -10, 75, -88, 94, 23, -106, -67, -4, 53, -91, -74, -64, 101, 70, 113, 100, 14, 67, 22, -27, -121, -45, + -11, -107, 64, -56, -101, 97, 62, 64, 65, 57, -18, -47, 96, -88, 38, -77, 107, 125, 39, -52, -83, -67, -27, + -20, -9, 27, -15, 69, 78, 74, -36, -114, 20, -121, -119, -55, 26, -50, -69, 16, -21, 84, 6, 66, 117, -39, 0, + 17, -39, -15, 49, -114, -101, -106, -113, -98, -81, 3, 18, -109, -122, -57, -19, 27, 2, 53, 8, -53, -11, + -73, -84, 9, 55, -33, 8, -93, 16, -103, -4, 117, -35, -63, 43, -97, -74, 48, 101, -108, 38, -54, 18, -36, + 105, -39, 21, 117, -81, 42, -15, -95, 79, -124, -59, -128, 64, 82, 85, -68, -79, 24, -84, 25, -113, 125, + -17, -20, -57, 50, -63, -13, -79, -60, 81, -104, 111, -84, 62, 123, -40, 12, -7, 65, -5, 23, 3, -91, -17, 2, + 49, -56, 73, 35, 46, -97, 38, -18, 14, 10, 26, 11, 122, 124, 124, -20, -110, -9, 26, 122, 59, 74, -123, -86, + 97, 0, 48, -14, 65, -50, -49, 40, 90, 65, 127, 75, 110, -76, 127, -41, 80, 6, 30, 61, -4, 27, -63, -100, + 115, -79, -87, 107, 66, 73, -14, 13, -98, -108, 55, 26, 58, -72, -103, -35, 46, -15, 45, 23, 84, 93, 31, 44, + -112, -41, 95, 22, 14, -114, 15, 2, 3, 1, 0, 1}; + @Before + public void before() { + ReflectionTestUtils.setField(kycExchangeFilter, "mapper", mapper); + ReflectionTestUtils.setField(kycExchangeFilter, "env", env); + } + @Test + public void checkAllowedAuthTypeBasedOnPolicyTest() { + AuthPolicy authPolicy = new AuthPolicy(); + authPolicy.setAuthType("demo"); + authPolicy.setMandatory(true); + try { + ReflectionTestUtils.invokeMethod(kycExchangeFilter, "checkAllowedAuthTypeBasedOnPolicy", new HashMap<>(), Collections.singletonList(authPolicy)); + } catch (UndeclaredThrowableException e) { + String detailMessage = e.getUndeclaredThrowable().getMessage(); + String[] error = detailMessage.split("-->"); + assertEquals("IDA-MPA-026", error[0].trim()); + assertEquals("Partner is unauthorised for KYC-Exchange", error[1].trim()); + assertTrue(e.getCause().getClass().equals(IdAuthenticationAppException.class)); + } + } +} + \ No newline at end of file diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/impl/VciServiceImplTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/impl/VciServiceImplTest.java new file mode 100644 index 00000000000..8ae4b80c7eb --- /dev/null +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/impl/VciServiceImplTest.java @@ -0,0 +1,347 @@ +package io.mosip.authentication.service.kyc.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import foundation.identity.jsonld.ConfigurableDocumentLoader; +import foundation.identity.jsonld.JsonLDException; +import info.weboftrust.ldsignatures.LdProof; +import info.weboftrust.ldsignatures.canonicalizer.URDNA2015Canonicalizer; +import io.mosip.authentication.common.service.entity.CredSubjectIdStore; +import io.mosip.authentication.common.service.helper.IdInfoHelper; +import io.mosip.authentication.common.service.repository.CredSubjectIdStoreRepository; +import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager; +import io.mosip.authentication.common.service.util.EnvUtil; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO; +import io.mosip.authentication.core.indauth.dto.VciCredentialsDefinitionRequestDTO; +import io.mosip.authentication.core.indauth.dto.VciExchangeRequestDTO; +import io.mosip.authentication.service.kyc.util.VCSchemaProviderUtil; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import org.json.simple.JSONObject; +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.*; + +@RunWith(SpringRunner.class) +@Import(EnvUtil.class) +public class VciServiceImplTest { + + @Mock + JSONObject vcContextJsonld; + + @Autowired + EnvUtil envUtil; + + @Mock + IdAuthSecurityManager securityManager; + + @Mock + CredSubjectIdStoreRepository csidStoreRepo; + + @Mock + LdProof.Builder builder; + + @Mock + URDNA2015Canonicalizer urdna2015Canonicalizer; + + @Mock + VCSchemaProviderUtil vcSchemaProviderUtil; + + /** The demo helper. */ + @Mock + IdInfoHelper idInfoHelper; + + @Mock + CbeffUtil cbeffUtil; + + @Mock + ObjectMapper objectMapper=new ObjectMapper(); + + @InjectMocks + VciServiceImpl vciServiceImpl; + + VciCredentialsDefinitionRequestDTO vciCredentialsDefinitionRequestDTO; + + VciExchangeRequestDTO vciExchangeRequestDTO; + + IdentityInfoDTO identityInfoDTO; + + List locale; + + Map> idInfo; + + String credSubjectId; + + + @Before + public void beforeTest(){ + + identityInfoDTO=new IdentityInfoDTO(); + identityInfoDTO.setLanguage("eng"); + identityInfoDTO.setValue("value"); + List list=new ArrayList<>(); + list.add(identityInfoDTO); + idInfo =new HashMap<>(); + idInfo.put("name",list); + + locale=new ArrayList<>(); + locale.add("eng"); + + vciExchangeRequestDTO = new VciExchangeRequestDTO(); + vciExchangeRequestDTO.setId("12345678901234567890123456789012"); + vciExchangeRequestDTO.setMetadata(new HashMap<>()) ; + vciExchangeRequestDTO.setRequestTime("2019-07-15T12:00:00.000Z"); + vciExchangeRequestDTO.setVcAuthToken("12345678901234567890123456789012"); + vciExchangeRequestDTO.setCredSubjectId("12345678901234567890123456789012"); + vciExchangeRequestDTO.setVcFormat("WLA"); + vciExchangeRequestDTO.setIndividualId("1234567890"); + vciExchangeRequestDTO.setIndividualIdType("UIN"); + + vciCredentialsDefinitionRequestDTO = new VciCredentialsDefinitionRequestDTO(); + vciCredentialsDefinitionRequestDTO.setContext(List.of("https://www.w3.org/2018/credentials/v1")); + vciCredentialsDefinitionRequestDTO.setType(List.of("VerifiableCredential")); + vciCredentialsDefinitionRequestDTO.setCredentialSubject(new HashMap<>()); + credSubjectId="12345:54321:ewogICAgImt0eSI6ICJSU0EiLAogICAgImUiOiAiQVFBQiIsCiAgICAidXNlIjogInNpZyIsCiAgICAia2lkIjogInBicy1GY1B6N1Jwbm42UUI1WG8xLWxrdVBEWHlxRlBZUzB5V296S0VpUjgiLAogICAgImFsZyI6ICJSUzI1NiIsCiAgICAibiI6ICJzSzhLTE55d0JoVVloYWhIREpTN0lPNkN2SkYxeTNmX0xsTEJvTV81eGFvcXVPckxDb084R0llaWJ1ai1YOWV0S3d1SkoycTdjdzRnTEJocXFOd2x3T2ZTOXZ2X1BnRTZkTTYtSDkxVVgtbGljQzh6YUFDSkdCV1N2TlVjSmtSNFJpOW5laGQ3NmRMSTJ5SDdlYVh3N0lRVERyMDVtSFFyR1ZaNVBVZTRMR3haZlVqcmxQUGttcTZfUTBIbk5RN1ZGTjVFLUxDejNvUWtKbHl4OTQyenhJdk5TV2V1enNMQU5xZWdSQzVWd3YtWlJtNmgxb1BNSWY1MThoZHdwaEhqeU5fRGs5djExYV8yT2VaNzd0T3Ria0RUaUxtamVLS1dTNXZldW1rOWMzTkw4OU00LS1yMFJMZ0Jrb3k1X0RMNHNmRXpSRnZYWVF0eHI4c3R1aURaRFEiCn0="; + + } + + @Test + public void addCredSubjectIdTestWithInvalidCredSubjectId_thenFail() throws IdAuthenticationBusinessException { + + try{ + vciServiceImpl.addCredSubjectId("12345:54321:MTIzNDU2Nzg5MA==","hash","123456789","12"); + }catch (IdAuthenticationBusinessException e){ + Assert.assertEquals("IDA-MLC-007",e.getErrorCode()); + } + } + + @Test + public void addCredSubjectIdTestWithValidDetailsAndWithoutSubIdList_thenPass() throws IdAuthenticationBusinessException { + vciServiceImpl.addCredSubjectId(credSubjectId,"hash","123456789","12"); + + } + + @Test + public void addCredSubjectIdTestWithValidDetailsWithSameVid_thenPass() throws IdAuthenticationBusinessException { + + List credSubjectIdList = new ArrayList<>(); + CredSubjectIdStore credSubjectIdStore=new CredSubjectIdStore(); + credSubjectIdStore.setCredSubjectId("12345"); + credSubjectIdStore.setId("12345"); + credSubjectIdStore.setIdVidHash("hash"); + credSubjectIdList.add(credSubjectIdStore); + credSubjectIdStore.setTokenId("token"); + Mockito.when(csidStoreRepo.findAllByCsidKeyHash(Mockito.anyString())).thenReturn(credSubjectIdList); + vciServiceImpl.addCredSubjectId(credSubjectId,"hash","token","12"); + + } + + @Test + public void addCredSubjectIdTestWithValidDetailsWithDiffSameVid_thenPass() throws IdAuthenticationBusinessException { + + List credSubjectIdList = new ArrayList<>(); + CredSubjectIdStore credSubjectIdStore=new CredSubjectIdStore(); + credSubjectIdStore.setCredSubjectId("12345"); + credSubjectIdStore.setId("12345"); + credSubjectIdStore.setIdVidHash("hash"); + credSubjectIdList.add(credSubjectIdStore); + credSubjectIdStore.setTokenId("token"); + Mockito.when(csidStoreRepo.findAllByCsidKeyHash(Mockito.anyString())).thenReturn(credSubjectIdList); + vciServiceImpl.addCredSubjectId(credSubjectId,"hashe","token","12"); + + } + + //TODO builder need to be fixed + @Test + public void buildVerifiableCredentialsTest() throws IdAuthenticationBusinessException, JsonLDException, GeneralSecurityException, IOException { + ReflectionTestUtils.setField(vciServiceImpl, "consentedIndividualAttributeName", "name"); + ReflectionTestUtils.setField(vciServiceImpl, "proofPurpose", "purpose"); + ReflectionTestUtils.setField(vciServiceImpl, "proofType", "proofType"); + ReflectionTestUtils.setField(vciServiceImpl,"verificationMethod","verificationMethod"); + ReflectionTestUtils.setField(vciServiceImpl,"confDocumentLoader",new ConfigurableDocumentLoader()); + Set allowedAttribute =new HashSet<>(); + allowedAttribute.add("name"); + + VciCredentialsDefinitionRequestDTO vciCredentialsDefinitionRequestDTO = new VciCredentialsDefinitionRequestDTO(); + vciCredentialsDefinitionRequestDTO.setContext(List.of("https://www.w3.org/2018/credentials/v1")); + vciCredentialsDefinitionRequestDTO.setType(List.of("VerifiableCredential")); + vciCredentialsDefinitionRequestDTO.setCredentialSubject(new HashMap<>()); + + + EnvUtil.setDateTimePattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Create a mock of the LdProof.Builder class + LdProof.Builder builderMock = Mockito.mock(LdProof.Builder.class,"RETURNS_SELF"); + + Mockito.when(builderMock.defaultContexts(Mockito.anyBoolean())).thenReturn(builderMock); + Mockito.when(builderMock.defaultTypes(Mockito.anyBoolean())).thenReturn(builderMock); + Mockito.when(builderMock.type(Mockito.anyString())).thenReturn(builderMock); + Mockito.when(builderMock.created(Mockito.any())).thenReturn(builderMock); + Mockito.when(builderMock.proofPurpose("purpose")).thenReturn(builderMock); + Mockito.when(builderMock.verificationMethod(Mockito.any())).thenReturn(builderMock); + + + LdProof ldProofMock = Mockito.mock(LdProof.class); + Mockito.when(builderMock.build()).thenReturn(ldProofMock); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + Mockito.when( vcContextJsonld.get("context")).thenReturn(new Object()); + Mockito.when(urdna2015Canonicalizer.canonicalize(Mockito.any(),Mockito.any())).thenReturn(new byte[4]); + + try{ + vciServiceImpl.buildVerifiableCredentials(credSubjectId,"ldp_vc" ,idInfo, locale, allowedAttribute, vciExchangeRequestDTO,"pusutokdn"); + }catch (Exception e){} + + } + + @Test + public void buildVerifiableCredentialswithjwt_vc_jsonTest() throws IdAuthenticationBusinessException { + + Set allowedAttribute =new HashSet<>(); + allowedAttribute.add("name"); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + Mockito.when( vcContextJsonld.get("context")).thenReturn(new Object()); + + try{ + vciServiceImpl.buildVerifiableCredentials(credSubjectId,"jwt_vc_json" ,idInfo, locale, allowedAttribute, vciExchangeRequestDTO,"pusutokdn"); + }catch (Exception e){} + + } + + @Test + public void buildVerifiableCredentialswithjwt_vc_jsonldTest() throws IdAuthenticationBusinessException { + + Set allowedAttribute =new HashSet<>(); + allowedAttribute.add("name"); + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + Mockito.when( vcContextJsonld.get("context")).thenReturn(new Object()); + + try{ + vciServiceImpl.buildVerifiableCredentials(credSubjectId,"jwt_vc_json-ld" ,idInfo, locale, allowedAttribute, vciExchangeRequestDTO,"pusutokdn"); + }catch (Exception e){} + + } + + @Test + public void buildVerifiableCredentialsWithFaceTest() throws Exception { + ReflectionTestUtils.setField(vciServiceImpl, "consentedIndividualAttributeName", "name"); + ReflectionTestUtils.setField(vciServiceImpl, "proofPurpose", "purpose"); + ReflectionTestUtils.setField(vciServiceImpl, "proofType", "proofType"); + ReflectionTestUtils.setField(vciServiceImpl,"verificationMethod","verificationMethod"); + ReflectionTestUtils.setField(vciServiceImpl,"confDocumentLoader",new ConfigurableDocumentLoader()); + + Set allowedAttribute =new HashSet<>(); + allowedAttribute.add("face"); + + EnvUtil.setDateTimePattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + Mockito.when( vcContextJsonld.get("context")).thenReturn(new Object()); + Mockito.when(urdna2015Canonicalizer.canonicalize(Mockito.any(),Mockito.any())).thenReturn(new byte[4]); + + List birDataFromXMLType =new ArrayList<>(); + BIR bir=new BIR(); + bir.setBdb(new byte[4]); + birDataFromXMLType.add(bir); + Mockito.when(cbeffUtil.getBIRDataFromXMLType(Mockito.any(),Mockito.anyString())).thenReturn(birDataFromXMLType); + Map faceEntityInfoMap = new HashMap<>(); + faceEntityInfoMap.put("Face","face"); + Mockito.when(idInfoHelper.getIdEntityInfoMap(Mockito.any(),Mockito.anyMap(),Mockito.any())).thenReturn(faceEntityInfoMap); + try{ + vciServiceImpl.buildVerifiableCredentials(credSubjectId,"ldp_vc" ,idInfo, locale, allowedAttribute, vciExchangeRequestDTO,"pusutokdn"); + }catch (Exception e){} + + } + + @Test + public void buildVerifiableCredentialsWithIdScemaTest() throws Exception { + ReflectionTestUtils.setField(vciServiceImpl, "consentedIndividualAttributeName", "name"); + ReflectionTestUtils.setField(vciServiceImpl, "proofPurpose", "purpose"); + ReflectionTestUtils.setField(vciServiceImpl, "proofType", "proofType"); + ReflectionTestUtils.setField(vciServiceImpl,"verificationMethod","verificationMethod"); + ReflectionTestUtils.setField(vciServiceImpl,"confDocumentLoader",new ConfigurableDocumentLoader()); + IdentityInfoDTO identityInfoDTO=new IdentityInfoDTO(); + identityInfoDTO.setLanguage("eng"); + identityInfoDTO.setValue("value"); + List list=new ArrayList<>(); + list.add(identityInfoDTO); + Map> idInfo =new HashMap<>(); + idInfo.put("info",list); + + List locale=new ArrayList<>(); + locale.add("eng"); + + Set allowedAttribute =new HashSet<>(); + allowedAttribute.add("id"); + + EnvUtil.setDateTimePattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + Mockito.when( vcContextJsonld.get("context")).thenReturn(new Object()); + Mockito.when(urdna2015Canonicalizer.canonicalize(Mockito.any(),Mockito.any())).thenReturn(new byte[4]); + + + List idInfoHelperList = new ArrayList<>(); + idInfoHelperList.add("info"); + Mockito.when(idInfoHelper.getIdentityAttributesForIdName(Mockito.anyString())).thenReturn(idInfoHelperList); + try{ + vciServiceImpl.buildVerifiableCredentials(credSubjectId,"ldp_vc" ,idInfo, locale, allowedAttribute, vciExchangeRequestDTO,"pusutokdn"); + }catch (Exception e){} + + } + + + @Test + public void buildVerifiableCredentialsWithInfoListTest() throws Exception { + ReflectionTestUtils.setField(vciServiceImpl, "consentedIndividualAttributeName", "name"); + ReflectionTestUtils.setField(vciServiceImpl, "proofPurpose", "purpose"); + ReflectionTestUtils.setField(vciServiceImpl, "proofType", "proofType"); + ReflectionTestUtils.setField(vciServiceImpl,"verificationMethod","verificationMethod"); + ReflectionTestUtils.setField(vciServiceImpl,"confDocumentLoader",new ConfigurableDocumentLoader()); + IdentityInfoDTO identityInfoDTO=new IdentityInfoDTO(); + identityInfoDTO.setLanguage("eng"); + identityInfoDTO.setValue("value"); + List list=new ArrayList<>(); + list.add(identityInfoDTO); + identityInfoDTO=new IdentityInfoDTO(); + identityInfoDTO.setLanguage("hin"); + identityInfoDTO.setValue("value"); + list.add(identityInfoDTO); + Map> idInfo =new HashMap<>(); + idInfo.put("info",list); + + List locale=new ArrayList<>(); + locale.add("eng"); + + Set allowedAttribute =new HashSet<>(); + allowedAttribute.add("id"); + + EnvUtil.setDateTimePattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + vciExchangeRequestDTO.setCredentialsDefinition(vciCredentialsDefinitionRequestDTO); + Mockito.when( vcContextJsonld.get("context")).thenReturn(new Object()); + Mockito.when(urdna2015Canonicalizer.canonicalize(Mockito.any(),Mockito.any())).thenReturn(new byte[4]); + + + List idInfoHelperList = new ArrayList<>(); + idInfoHelperList.add("info"); + Mockito.when(idInfoHelper.getIdentityAttributesForIdName(Mockito.anyString())).thenReturn(idInfoHelperList); + try{ + vciServiceImpl.buildVerifiableCredentials(credSubjectId,"ldp_vc" ,idInfo, locale, allowedAttribute, vciExchangeRequestDTO,"pusutokdn"); + }catch (Exception e){} + + } +} diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/util/VCSchemaProviderUtilTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/util/VCSchemaProviderUtilTest.java new file mode 100644 index 00000000000..60db674d8e8 --- /dev/null +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/util/VCSchemaProviderUtilTest.java @@ -0,0 +1,101 @@ +package io.mosip.authentication.service.kyc.util; + +import com.apicatalog.jsonld.JsonLdError; +import com.apicatalog.jsonld.document.JsonDocument; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.authentication.core.exception.IdAuthUncheckedException; +import io.mosip.authentication.core.exception.IdAuthenticationBusinessException; +import org.json.simple.JSONObject; +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.web.client.RestTemplate; + +import java.io.IOException; +import java.io.StringReader; +import java.util.Map; + +@RunWith(MockitoJUnitRunner.class) +public class VCSchemaProviderUtilTest { + + @InjectMocks + private VCSchemaProviderUtil vcSchemaProviderUtil; + + @Mock + private RestTemplate restTemplate; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGetVCContextSchema() { + String configServerFileStorageUrl = "http://example.com"; + String uri = "vc-context-schema.json"; + String vcContextJson = "{\"vc\": \"context\"}"; + JsonDocument expectedJsonDocument = null; + try { + expectedJsonDocument = JsonDocument.of(new StringReader(vcContextJson)); + } catch (JsonLdError e) { + throw new RuntimeException(e); + } + + Mockito.when(restTemplate.getForObject(configServerFileStorageUrl + uri, String.class)) + .thenReturn(vcContextJson); + JsonDocument result = vcSchemaProviderUtil.getVCContextSchema(configServerFileStorageUrl, uri); + Assert.assertEquals(expectedJsonDocument.getJsonContent(), result.getJsonContent()); + Mockito.verify(restTemplate).getForObject(configServerFileStorageUrl + uri, String.class); + } + + @Test + public void testGetVCContextSchema_throwsException() { + String configServerFileStorageUrl = "http://example.com"; + String uri = "vc-context-schema.json"; + String vcContextJson = ""; + Mockito.when(restTemplate.getForObject(configServerFileStorageUrl + uri, String.class)) + .thenReturn(vcContextJson); + Assert.assertThrows(IdAuthUncheckedException.class,()->vcSchemaProviderUtil.getVCContextSchema(configServerFileStorageUrl, uri)); + } + + @Test + public void testGetVCContextData() throws IdAuthenticationBusinessException { + String configServerFileStorageUrl = "http://example.com"; + String uri = "/vc-context-data.json"; + String vcContextData = "{\"vc\": \"data\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + Map expectedMap; + + try { + expectedMap = objectMapper.readValue(vcContextData, new TypeReference>(){}); + } catch (IOException e) { + Assert.fail("Error parsing JSON: " + e.getMessage()); + return; + } + + JSONObject expectedJsonObject = new JSONObject(expectedMap); + Mockito.when(restTemplate.getForObject(configServerFileStorageUrl + uri, String.class)) + .thenReturn(vcContextData); + JSONObject result = vcSchemaProviderUtil.getVCContextData(configServerFileStorageUrl, uri, objectMapper); + Assert.assertEquals(expectedJsonObject, result); + Mockito.verify(restTemplate).getForObject(configServerFileStorageUrl + uri, String.class); + } + + @Test + public void testGetVCContextData_throwsException() throws IdAuthenticationBusinessException{ + String configServerFileStorageUrl = "http://example.com"; + String uri = "/vc-context-data.json"; + String vcContextData = ""; + Mockito.when(restTemplate.getForObject(configServerFileStorageUrl + uri, String.class)) + .thenReturn(vcContextData); + Assert.assertThrows(IdAuthenticationBusinessException.class,()->vcSchemaProviderUtil.getVCContextData(configServerFileStorageUrl,uri, new ObjectMapper())); + } + +} \ No newline at end of file diff --git a/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycExchangeRequestValidatorTest.java b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycExchangeRequestValidatorTest.java new file mode 100644 index 00000000000..ba9b619a332 --- /dev/null +++ b/authentication/authentication-service/src/test/java/io/mosip/authentication/service/kyc/validator/KycExchangeRequestValidatorTest.java @@ -0,0 +1,114 @@ +package io.mosip.authentication.service.kyc.validator; + +import io.mosip.authentication.common.service.helper.IdInfoHelper; +import io.mosip.authentication.common.service.util.EnvUtil; +import io.mosip.authentication.common.service.validator.AuthRequestValidator; +import io.mosip.authentication.core.indauth.dto.KycExchangeRequestDTO; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; +import org.springframework.web.context.WebApplicationContext; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +@RunWith(SpringRunner.class) +@WebMvcTest +@ContextConfiguration(classes = { TestContext.class, WebApplicationContext.class }) +@Import(EnvUtil.class) +public class KycExchangeRequestValidatorTest { + @InjectMocks + KycExchangeRequestValidator kycExchangeRequestValidator; + @Mock + IdInfoHelper idInfoHelper; + @InjectMocks + AuthRequestValidator authRequestValidator; + @Before + public void before() { + ReflectionTestUtils.setField(kycExchangeRequestValidator, "idInfoHelper", idInfoHelper); + ReflectionTestUtils.setField(authRequestValidator, "idInfoHelper", idInfoHelper); + } + @Test + public void testSupportTrue() { + assertTrue(kycExchangeRequestValidator.supports(KycExchangeRequestDTO.class)); + } + @Test + public void testSupportFalse() { + assertFalse(kycExchangeRequestValidator.supports(KycAuthRequestValidator.class)); + } + @Test + @Ignore + public void testValidate_ValidRequest_NoErrors() { + KycExchangeRequestDTO kycExchangeRequestDTO = new KycExchangeRequestDTO(); + kycExchangeRequestDTO.setId("id"); + kycExchangeRequestDTO.setRequestTime(ZonedDateTime.now() + .format(DateTimeFormatter.ofPattern(EnvUtil.getDateTimePattern())).toString()); + kycExchangeRequestDTO.setKycToken("token"); + kycExchangeRequestDTO.setTransactionID("1234567890"); + List consentObtained=new ArrayList<>(); + consentObtained.add("phone"); + consentObtained.add("email"); + kycExchangeRequestDTO.setConsentObtained(consentObtained); + List locales=new ArrayList<>(); + locales.add("en"); + kycExchangeRequestDTO.setLocales(locales); + kycExchangeRequestDTO.setRespType("abc"); + Map metadata=new HashMap<>(); + kycExchangeRequestDTO.setMetadata(metadata); + Errors errors = new BeanPropertyBindingResult(kycExchangeRequestDTO, "kycExchangeRequestDTO"); + Mockito.when(idInfoHelper.isMatchtypeEnabled(Mockito.any())).thenReturn(Boolean.TRUE); + kycExchangeRequestValidator.validate(kycExchangeRequestDTO, errors); + Assert.assertFalse(errors.hasErrors()); + } + @Test + public void testValidate_NullRequest_InvalidInputParameterError() { + KycExchangeRequestDTO kycExchangeRequestDTO = new KycExchangeRequestDTO(); + Errors errors = new BeanPropertyBindingResult(kycExchangeRequestDTO, "kycExchangeRequestDTO"); + kycExchangeRequestValidator.validate(kycExchangeRequestDTO, errors); + Mockito.when(idInfoHelper.isMatchtypeEnabled(Mockito.any())).thenReturn(Boolean.TRUE); + Assert.assertTrue(errors.hasErrors()); + Assert.assertEquals("IDA-MLC-006", errors.getFieldError().getCode()); + } + @Test + public void testValidate_InvalidKycToken_MissingInputParameterError() { + KycExchangeRequestDTO request = new KycExchangeRequestDTO(); + request.setRequestTime("2023-10-31 10:00:00"); + request.setKycToken(null); + request.setTransactionID("1234567890"); + Errors errors = new BeanPropertyBindingResult(request, "kycExchangeRequestDTO"); + kycExchangeRequestValidator.validate(request, errors); + Mockito.when(idInfoHelper.isMatchtypeEnabled(Mockito.any())).thenReturn(Boolean.TRUE); + Assert.assertTrue(errors.hasErrors()); + Assert.assertEquals("IDA-MLC-009", errors.getFieldError().getCode()); + } + @Test + public void testValidate_EmptyConsentObtainedList_MissingInputParameterError() { + KycExchangeRequestDTO request = new KycExchangeRequestDTO(); + request.setRequestTime("2023-10-31 10:00:00"); + request.setKycToken("exampleToken"); + request.setTransactionID("exampleTransactionID"); + request.setConsentObtained(new ArrayList<>()); + Errors errors = new BeanPropertyBindingResult(request, "kycExchangeRequestDTO"); + Mockito.when(idInfoHelper.isMatchtypeEnabled(Mockito.any())).thenReturn(Boolean.TRUE); + kycExchangeRequestValidator.validate(request, errors); + Assert.assertTrue(errors.hasErrors()); + Assert.assertEquals("IDA-MLC-009", errors.getFieldError().getCode()); + } +} \ No newline at end of file diff --git a/authentication/esignet-integration-impl/pom.xml b/authentication/esignet-integration-impl/pom.xml index 89801462db7..c46ce3f75b7 100644 --- a/authentication/esignet-integration-impl/pom.xml +++ b/authentication/esignet-integration-impl/pom.xml @@ -6,9 +6,9 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT esignet-integration-impl esignet-integration-impl e-Signet Integration Implementation Library @@ -24,7 +24,7 @@ 4.13.1 test - + org.projectlombok lombok @@ -43,7 +43,7 @@ 1.2.0-SNAPSHOT provided - + io.mosip.kernel kernel-keymanager-service @@ -74,4 +74,4 @@ 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/IdaKycAuthRequest.java b/authentication/esignet-integration-impl/src/main/java/io/mosip/authentication/esignet/integration/dto/IdaKycAuthRequest.java index 086d71af66e..1465bb7129b 100644 --- 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 @@ -37,6 +37,7 @@ public static class AuthRequest { private String timestamp; private List biometrics; private List keyBindedTokens; + private String password; } @Data 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 203c80d38f9..5a95185da93 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 @@ -259,6 +259,8 @@ private void buildAuthRequest(AuthChallenge authChallenge, IdaKycAuthRequest.Aut list.add(keyBindedToken); authRequest.setKeyBindedTokens(list); break; + case "PWD" : authRequest.setPassword(authChallenge.getChallenge()); + break; default: throw new NotImplementedException("KYC auth not implemented"); } 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 245a7821ebf..2848be4f3cb 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 @@ -6,22 +6,14 @@ 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.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.KycAuthException; -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; +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.cache.annotation.CacheEvict; -import org.springframework.cache.annotation.Cacheable; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; @@ -32,10 +24,20 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +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 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 index 8528d4b3d91..7e66a33a45e 100644 --- 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 @@ -170,6 +170,27 @@ public void setAuthRequest_withOTPChallengeType_thenPass() throws Exception { 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<>(); 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 new file mode 100644 index 00000000000..ceda8fd7c41 --- /dev/null +++ b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaAuditPluginImplTest.java @@ -0,0 +1,160 @@ +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/IdaVCIssuancePluginImplTest.java b/authentication/esignet-integration-impl/src/test/java/io/mosip/authentication/esignet/integration/service/IdaVCIssuancePluginImplTest.java index b37730feed7..fe3bb52f8c6 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 @@ -81,7 +81,7 @@ public void getVerifiableCredentialWithLinkedDataProof_withValidDetails_thenPass oidcTransaction.setKycToken("kycToken"); oidcTransaction.setAuthTransactionId("authTransactionId"); oidcTransaction.setRelyingPartyId("relyingPartyId"); - oidcTransaction.setClaimsLocales(new String[]{"eng"}); + oidcTransaction.setClaimsLocales(new String[]{"en-US", "en", "en-CA", "fr-FR", "fr-CA"}); IdaResponseWrapper> mockResponseWrapper = new IdaResponseWrapper<>(); IdaVcExchangeResponse mockResponse = new IdaVcExchangeResponse<>(); diff --git a/authentication/pom.xml b/authentication/pom.xml index c489e8666e8..3928a0df95a 100644 --- a/authentication/pom.xml +++ b/authentication/pom.xml @@ -5,7 +5,7 @@ io.mosip.authentication authentication-parent - 1.2.0.1-B5 + 1.2.0.1-SNAPSHOT pom id-authentication @@ -95,7 +95,7 @@ 1.2.0.1-B1 ${kernel.parent.version} - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT ${kernel.parent.version} ${kernel.parent.version} ${kernel.parent.version} @@ -112,7 +112,8 @@ 20180130 1.2.0.1-B1 ${kernel.parent.version} - 1.2.0 + ${kernel.parent.version} + 1.2.0.1-B3 11 @@ -220,6 +221,17 @@ + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.12.0 + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + 2.12.0 + + io.mosip.kernel kernel-core @@ -249,6 +261,12 @@ ${spring.boot.version} true + + io.mosip.kernel + kernel-openid-bridge-api + ${kernel-openid-bridge-api.version} + provided + @@ -423,6 +441,16 @@ + + diff --git a/db_scripts/mosip_ida/ddl.sql b/db_scripts/mosip_ida/ddl.sql index 64e5c0a73e0..3890ea0955d 100644 --- a/db_scripts/mosip_ida/ddl.sql +++ b/db_scripts/mosip_ida/ddl.sql @@ -28,4 +28,5 @@ \ir ddl/ida-anonymous_profile.sql \ir ddl/ida-ident_binding_cert_store.sql \ir ddl/ida-kyc_token_store.sql -\ir ddl/ida-oidc_client_data.sql \ No newline at end of file +\ir ddl/ida-oidc_client_data.sql +\ir ddl/ida-cred_subject_id_store.sql \ No newline at end of file diff --git a/db_scripts/mosip_ida/ddl/ida-credential_event_store.sql b/db_scripts/mosip_ida/ddl/ida-credential_event_store.sql index c589b421f24..f2cc8474bec 100644 --- a/db_scripts/mosip_ida/ddl/ida-credential_event_store.sql +++ b/db_scripts/mosip_ida/ddl/ida-credential_event_store.sql @@ -18,7 +18,7 @@ CREATE TABLE ida.credential_event_store( event_id character varying(36) NOT NULL, event_topic character varying(256) NOT NULL, - credential_transaction_id character varying(36) NOT NULL, + credential_transaction_id character varying(64) NOT NULL, publisher character varying(128), published_on_dtimes timestamp, event_object character varying, diff --git a/db_upgrade_scripts/mosip_ida/sql/1.2.0.1-B5_to_1.2.0.1_rollback.sql b/db_upgrade_scripts/mosip_ida/sql/1.2.0.1-B5_to_1.2.0.1_rollback.sql new file mode 100644 index 00000000000..1ea8a6e97f2 --- /dev/null +++ b/db_upgrade_scripts/mosip_ida/sql/1.2.0.1-B5_to_1.2.0.1_rollback.sql @@ -0,0 +1,3 @@ +\echo 'Upgrade Queries not required for the transition from 1.2.0.1-B5 to 1.2.0.1' + +ALTER TABLE ida.credential_event_store ALTER COLUMN credential_transaction_id type character varying(36); diff --git a/db_upgrade_scripts/mosip_ida/sql/1.2.0.1-B5_to_1.2.0.1_upgrade.sql b/db_upgrade_scripts/mosip_ida/sql/1.2.0.1-B5_to_1.2.0.1_upgrade.sql new file mode 100644 index 00000000000..36efab138ca --- /dev/null +++ b/db_upgrade_scripts/mosip_ida/sql/1.2.0.1-B5_to_1.2.0.1_upgrade.sql @@ -0,0 +1,3 @@ +\echo 'Upgrade Queries not required for transition from 1.2.0.1-B5 to 1.2.0.1' + +ALTER TABLE ida.credential_event_store ALTER COLUMN credential_transaction_id type character varying(64);