Skip to content

Commit

Permalink
Merge pull request #155 from mahammedtaheer/1.2.0.1-B2
Browse files Browse the repository at this point in the history
Merging Code from develop to 1.2.0.1-B2
  • Loading branch information
mahammedtaheer authored Jan 3, 2023
2 parents 34658d0 + 0097e69 commit b506426
Show file tree
Hide file tree
Showing 28 changed files with 303 additions and 98 deletions.
16 changes: 8 additions & 8 deletions .github/workflows/push_trigger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,17 @@ jobs:

- name: Publish the maven package
run: |
cd kernel && mvn -B deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml
cd kernel && mvn -B deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.OSSRH_SNAPSHOT_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml
env:
GITHUB_TOKEN: ${{secrets.RELEASE_TOKEN}}
GPG_TTY: $(tty)
- uses: 8398a7/action-slack@v3
with:
status: ${{ job.status }}
fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message)
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
if: failure() # Pick up events even if the job fails or is canceled.
# - uses: 8398a7/action-slack@v3
# with:
# status: ${{ job.status }}
# fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message)
# env:
# SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
# if: failure() # Pick up events even if the job fails or is canceled.


docker-kernel-keymanager-service:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[![Maven Package upon a push](https://github.com/mosip/keymanager/actions/workflows/push_trigger.yml/badge.svg?branch=release-1.2.0.1)](https://github.com/mosip/keymanager/actions/workflows/push_trigger.yml)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=mosip_keymanager&metric=alert_status)](https://sonarcloud.io/dashboard?branch=release-1.2.0.1&id=mosip_keymanager)
[![Maven Package upon a push](https://github.com/mosip/keymanager/actions/workflows/push_trigger.yml/badge.svg?branch=develop)](https://github.com/mosip/keymanager/actions/workflows/push_trigger.yml)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?branch=master&project=mosip_keymanager&metric=alert_status)](https://sonarcloud.io/dashboard?branch=develop&id=mosip_keymanager)

# Key Manager

Expand Down
1 change: 1 addition & 0 deletions db_release_scripts/mosip_keymgr/sql/1.2.0-release.sql
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ ALTER TABLE keymgr.key_policy_def ADD COLUMN access_allowed character varying(10

insert into keymgr.key_policy_def(app_id, key_validity_duration, is_active, cr_by, cr_dtimes, pre_expire_days, access_allowed) values('ADMIN_SERVICES',1095,TRUE,'mosipadmin',now(),60,'NA');
insert into keymgr.key_policy_def(app_id, key_validity_duration, is_active, cr_by, cr_dtimes, pre_expire_days, access_allowed) values('RESIDENT',1095,TRUE,'mosipadmin',now(),60,'NA');
insert into keymgr.key_policy_def(app_id, key_validity_duration, is_active, cr_by, cr_dtimes, pre_expire_days, access_allowed) values('COMPLIANCE_TOOLKIT',1095,TRUE,'mosipadmin',now(),60,'NA');


-- updating default values for pre_expire_days & access_allowed columns
Expand Down
2 changes: 1 addition & 1 deletion db_release_scripts/mosip_keymgr/sql/1.2.0-revoke.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
\c mosip_keymgr sysadmin

delete from keymgr.key_policy_def where app_id in ('ADMIN_SERVICES','RESIDENT');
delete from keymgr.key_policy_def where app_id in ('ADMIN_SERVICES','RESIDENT','COMPLIANCE_TOOLKIT');


ALTER TABLE keymgr.key_alias DROP COLUMN IF EXISTS uni_ident;
Expand Down
3 changes: 2 additions & 1 deletion db_scripts/mosip_keymgr/dml/keymgr-key_policy_def.csv
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ BASE,730,TRUE,mosipadmin,now(),30,NA
PMS,1460,TRUE,mosipadmin,now(),395,NA
RESIDENT,1095,TRUE,mosipadmin,now(),60,NA
ADMIN_SERVICES,1095,TRUE,mosipadmin,now(),60,NA
DIGITAL_CARD,1095,TRUE,mosipadmin,now(),60,NA
DIGITAL_CARD,1095,TRUE,mosipadmin,now(),60,NA
COMPLIANCE_TOOLKIT,1095,TRUE,mosipadmin,now(),60,NA
1 change: 1 addition & 0 deletions db_scripts/mosip_keymgr/dml/keymgr-key_policy_def_h.csv
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ DATASHARE,1095,TRUE,mosipadmin,now(),now()
CREDENTIAL_SERVICE,1095,TRUE,mosipadmin,now(),now()
RESIDENT,1095,TRUE,mosipadmin,now(),now()
ADMIN_SERVICES,1095,TRUE,mosipadmin,now(),now()
DIGITAL_CARD,1095,TRUE,mosipadmin,now(),now()
2 changes: 1 addition & 1 deletion kernel/kernel-keymanager-service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<groupId>io.mosip.kernel</groupId>

<artifactId>kernel-keymanager-service</artifactId>
<version>1.2.0.1-B1</version>
<version>1.2.0.1-B2-SNAPSHOT</version>
<name>kernel-keymanager-service</name>
<description>Mosip commons project </description>
<url>https://github.com/mosip/commons</url>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,55 +144,4 @@ public ResponseWrapper<CryptoWithPinResponseDto> decryptWithPin(
responseDto.setResponse(cryptomanagerService.decryptWithPin(requestDto.getRequest()));
return responseDto;
}

/**
* Controller for Encrypt the data & encrypt hash of the data with same session
* key.
*
* @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request
* @return {@link CryptomanagerResponseDto} encrypted Data
*/
@Operation(summary = "Encrypt the data & encrypt hash of the data with same session key", description = "Encrypt the data & encrypt hash of the data with same session key", tags = {
"cryptomanager" })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success or you may find errors in error array in response"),
@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))) })
//@PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')")
@ResponseFilter
@PreAuthorize("hasAnyRole(@cryptoManagerAuthRoles.getPostencryptdt())")
@PostMapping(value = "/encryptDt", produces = "application/json")
public ResponseWrapper<CryptomanagerResponseDto> encryptDt(
@ApiParam("Salt and Data to encrypt in BASE64 encoding with meta-data") @RequestBody @Valid RequestWrapper<CryptomanagerRequestDto> cryptomanagerRequestDto) {
ResponseWrapper<CryptomanagerResponseDto> response = new ResponseWrapper<>();
response.setResponse(cryptomanagerService.encrypt(cryptomanagerRequestDto.getRequest()));
return response;
}

/**
* Controller for Decrypt the data and data hash. Compares the decrypted hash
* and hash of decrypted data if hash matches data will be returned otherwise
* throws exception.
*
* @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request
* @return {@link CryptomanagerResponseDto} decrypted Data
*/
@Operation(summary = "Decrypt the data & encrypt hash of the data with same session key", description = "Decrypt the data & encrypt hash of the data with same session key", tags = {
"cryptomanager" })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success or you may find errors in error array in response"),
@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))) })
//@PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')")
@PreAuthorize("hasAnyRole(@cryptoManagerAuthRoles.getPostdecryptdt())")
@ResponseFilter
@PostMapping(value = "/decryptDt", produces = "application/json")
public ResponseWrapper<CryptomanagerResponseDto> decryptDt(
@ApiParam("Salt and Data to decrypt in BASE64 encoding with meta-data") @RequestBody @Valid RequestWrapper<CryptomanagerRequestDto> cryptomanagerRequestDto) {
ResponseWrapper<CryptomanagerResponseDto> response = new ResponseWrapper<>();
response.setResponse(cryptomanagerService.decrypt(cryptomanagerRequestDto.getRequest()));
return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ public class KeyGeneratorUtils {
* Bouncy-Castle provider instance
*/
private static BouncyCastleProvider provider;

private static SecureRandom random;

static {
provider = init();
random = new SecureRandom();
}

/**
Expand All @@ -52,7 +55,6 @@ public static javax.crypto.KeyGenerator getKeyGenerator(String algorithmName, in
KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(),
KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e);
}
SecureRandom random = new SecureRandom();
generator.init(keylength, random);
return generator;
}
Expand All @@ -74,7 +76,6 @@ public static KeyPairGenerator getKeyPairGenerator(String algorithmName, int key
KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(),
KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e);
}
SecureRandom random = new SecureRandom();
generator.initialize(keylength, random);
return generator;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,8 @@ private KeymanagerConstant() {
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT);

public static final String UNDER_SCORE = "_";

public static final String COMPONENT_MASTER_KEY_DUMMY_REF = "COMP_MASTER";

public static final String ALL_GET_CERTIFICATES = "Request received to get all the Certificates";
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public enum KeymanagerErrorConstant {

MORE_THAN_ONE_KEY_FOUND("KER-KMS-023", "More than one key alias found for the provided thumbprint."),

APP_ID_REFERENCE_ID_NOT_MATCHING("KER-KMS-024", "Application Id & Reference Id not matching with the inputted thumbprint."),
APP_ID_REFERENCE_ID_NOT_MATCHING("KER-KMS-024", "Application Id & Reference Id not matching with the input thumbprint."),

KEY_NOT_FOUND_BY_THUMBPRINT("KER-KMS-025", "Key Not found for the thumbprint prepended in encrypted data."),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.mosip.kernel.core.http.RequestWrapper;
import io.mosip.kernel.core.http.ResponseFilter;
import io.mosip.kernel.core.http.ResponseWrapper;
import io.mosip.kernel.keymanagerservice.dto.AllCertificatesDataResponseDto;
import io.mosip.kernel.keymanagerservice.dto.CSRGenerateRequestDto;
import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto;
import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto;
Expand Down Expand Up @@ -227,4 +228,30 @@ public ResponseWrapper<RevokeKeyResponseDto> revokeKey(
response.setResponse(keymanagerService.revokeKey(revokeKeyRequestDto.getRequest()));
return response;
}

/**
* Request to get all the Certificates for the Provided APP ID & REF ID.
*
* @param applicationId Application id of the application requesting Certificate
* @param referenceId Reference id of the application requesting Certificate. Blank in case of Master Key.
* @return {@link KeyPairGenerateResponseDto} instance
*/
@Operation(summary = "Request to get all the certificates for the Provided APP ID & REF ID", description = "Request to get all the certificates for the Provided APP ID & REF ID", tags = { "keymanager" })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success or you may find errors in error array in response"),
@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))) })
//@PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')")
@PreAuthorize("hasAnyRole(@KeyManagerAuthRoles.getGetgetcertificate())")
@ResponseFilter
@GetMapping(value = "/getAllCertificates")
public ResponseWrapper<AllCertificatesDataResponseDto> getAllCertificates(
@ApiParam("Id of application") @RequestParam("applicationId") String applicationId,
@ApiParam("Refrence Id as metadata") @RequestParam("referenceId") Optional<String> referenceId) {

ResponseWrapper<AllCertificatesDataResponseDto> response = new ResponseWrapper<>();
response.setResponse(keymanagerService.getAllCertificates(applicationId, referenceId));
return response;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.mosip.kernel.keymanagerservice.dto;

import java.time.LocalDateTime;

import com.fasterxml.jackson.annotation.JsonFormat;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* Response class for all Certificates Data.
*
* @author Mahammed Taheer
* @since 1.2.1
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "Class representing a All Certificates Data Response")
public class AllCertificatesDataResponseDto {

/**
* Field for certificate
*/
private CertificateDataResponseDto[] allCertificates;


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package io.mosip.kernel.keymanagerservice.dto;

import java.time.LocalDateTime;

import com.fasterxml.jackson.annotation.JsonFormat;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* Response class for Certificate Data.
*
* @author Mahammed Taheer
* @since 1.2.1
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "Class representing a Certificate Data Response")
public class CertificateDataResponseDto {

/**
* Field for certificate
*/
@ApiModelProperty(notes = "X509 certificate", required = true)
private String certificateData;

/**
* Key creation time
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@ApiModelProperty(notes = "Timestamp of issuance of certificate", required = true)
private LocalDateTime issuedAt;

/**
* Key expiry time
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@ApiModelProperty(notes = "Timestamp of expiry of certificate", required = true)
private LocalDateTime expiryAt;

/**
* Field for certificate
*/
@ApiModelProperty(notes = "Unique Identifier of the key", required = true)
private String keyId;


}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ public class SignatureCertificate {
* The string keystore provider name
*/
private String providerName;

/**
* The string for key unique identifier.
*/
private String uniqueIdentifier;


@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,9 +300,11 @@ public KeyStore getKeyAlias(String certThumbprint, String appIdRefIdKey, String

// Duplicate check required because before caching comparison of app id & reference id is required.
String foundDBAppIdRefId = foundKeyAlias.getApplicationId() + KeymanagerConstant.HYPHEN + foundKeyAlias.getReferenceId();
if (!foundDBAppIdRefId.equals(appIdRefIdKey)){
// Checking for master key is used during encryption time.
String foundDBAppId = foundKeyAlias.getApplicationId();
if (!foundDBAppIdRefId.equals(appIdRefIdKey) && !foundDBAppId.equals(applicationId)){
LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY,
"AppId & Reference Id not matching with the inputted thumbprint value(helper).");
"AppId & Reference Id not matching with the input thumbprint value(helper).");
throw new KeymanagerServiceException(KeymanagerErrorConstant.APP_ID_REFERENCE_ID_NOT_MATCHING.getErrorCode(),
KeymanagerErrorConstant.APP_ID_REFERENCE_ID_NOT_MATCHING.getErrorMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,16 +137,22 @@ private SymmetricKeyResponseDto decryptSymmetricKeyWithKeyIdentifier(String appl
io.mosip.kernel.keymanagerservice.entity.KeyStore dbKeyStore = cacheKeyStore.getOrDefault(certThumbprintHex, null);

String appIdRefIdKey = applicationId + KeymanagerConstant.HYPHEN + referenceId;
String compMasterKeyRefId = applicationId + KeymanagerConstant.HYPHEN + KeymanagerConstant.COMPONENT_MASTER_KEY_DUMMY_REF;
if(Objects.isNull(dbKeyStore)) {
dbKeyStore = dbHelper.getKeyAlias(certThumbprintHex, appIdRefIdKey, applicationId, referenceId);
cacheKeyStore.put(certThumbprintHex, dbKeyStore);
cacheReferenceIds.put(certThumbprintHex, appIdRefIdKey);
// Added condition to handle issue related to decryption error with Master key.
if (Objects.isNull(dbKeyStore.getPrivateKey())) {
cacheReferenceIds.put(certThumbprintHex, compMasterKeyRefId);
} else {
cacheReferenceIds.put(certThumbprintHex, appIdRefIdKey);
}
}

String cachedRefId = cacheReferenceIds.getOrDefault(certThumbprintHex, null);
if (!appIdRefIdKey.equals(cachedRefId)){
if (!appIdRefIdKey.equals(cachedRefId) && !compMasterKeyRefId.equals(cachedRefId)){
LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY,
"Application Id & Reference ID not matching with the inputted thumbprint value(decrypt).");
"Application Id & Reference ID not matching with the input thumbprint value(decrypt).");
throw new KeymanagerServiceException(KeymanagerErrorConstant.APP_ID_REFERENCE_ID_NOT_MATCHING.getErrorCode(),
KeymanagerErrorConstant.APP_ID_REFERENCE_ID_NOT_MATCHING.getErrorMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Optional;

import io.mosip.kernel.keymanagerservice.dto.AllCertificatesDataResponseDto;
import io.mosip.kernel.keymanagerservice.dto.CSRGenerateRequestDto;
import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto;
import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto;
Expand Down Expand Up @@ -115,6 +116,15 @@ public SignatureCertificate getSignatureCertificate(String applicationId, Option
* @return {@link RevokeKeyResponseDto} instance
*/
public RevokeKeyResponseDto revokeKey(RevokeKeyRequestDto revokeKeyRequestDto);

/**
* Function to get all the certificates for the provided appId & refId.
*
* @param Application ID appId
* @param Reference ID refId
* @return {@link AllCertificatesDataResponseDto} instance
*/
public AllCertificatesDataResponseDto getAllCertificates(String appId, Optional<String> refId);

}

Loading

0 comments on commit b506426

Please sign in to comment.