Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Credissuer vc download changes #90

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions sunbird-rc-certify-integration-impl/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
<git-commit-id-plugin.version>3.0.1</git-commit-id-plugin.version> <!-- need to check the version-->
<maven.jacoco.version>0.8.11</maven.jacoco.version>
<maven-javadoc-plugin.version>3.6.3</maven-javadoc-plugin.version>
<kernel-keymanager-service.version>1.3.0-beta.1</kernel-keymanager-service.version>
</properties>
<dependencies>
<dependency>
Expand All @@ -58,13 +59,54 @@
<scope>provided</scope>
</dependency>

<dependency>
<groupId>io.mosip.esignet</groupId>
<artifactId>esignet-core</artifactId>
<version>1.4.1</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.mosip.esignet</groupId>
<artifactId>esignet-integration-api</artifactId>
<version>1.4.1</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>compile</scope>
<version>1.18.30</version>
</dependency>

<dependency>
<groupId>io.mosip.kernel</groupId>
<artifactId>kernel-keymanager-service</artifactId>
<version>${kernel-keymanager-service.version}</version>
<scope>provided</scope>
<classifier>lib</classifier>
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import org.springframework.cache.CacheManager;
import org.springframework.http.HttpHeaders;

import io.mosip.esignet.core.dto.OIDCTransaction;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
Expand All @@ -46,8 +51,21 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.PrintWriter;
import java.util.Base64;
import java.util.Objects;

import java.time.ZoneOffset;
import java.time.LocalDateTime;

import javax.crypto.Cipher;
import java.security.Key;
import io.mosip.kernel.core.keymanager.spi.KeyStore;
import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant;
import io.mosip.kernel.keymanagerservice.entity.KeyAlias;
import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper;

@ConditionalOnProperty(value = "mosip.certify.integration.vci-plugin", havingValue = "SunbirdRCVCIssuancePlugin")
@Component
Expand All @@ -74,23 +92,55 @@ public class SunbirdRCVCIssuancePlugin implements VCIssuancePlugin {

private final String FILTER_EQUALS_OPERATOR = "eq";

public static final String AES_CIPHER_FAILED = "aes_cipher_failed";

public static final String OIDC_SERVICE_APP_ID = "CERTIFY_SERVICE";

private final String PSUT_TOKEN="psut";

public static final String NO_UNIQUE_ALIAS = "no_unique_alias";

private Base64.Decoder urlSafeDecoder = Base64.getUrlDecoder();

@Autowired
Environment env;

@Autowired
ObjectMapper mapper;

@Autowired
private KeyStore keyStore;

@Autowired
private RestTemplate restTemplate;

@Autowired
private KeymanagerDBHelper dbHelper;

@Value("${mosip.certify.vciplugin.sunbird-rc.issue-credential-url}")
String issueCredentialUrl;

@Value("${io.credissuer.com.get-credential-url}")
String getCredentialUrl;

@Value("${mosip.certify.cache.secure.individual-id}")
private boolean secureIndividualId;

@Value("${mosip.certify.cache.store.individual-id}")
private boolean storeIndividualId;

@Value("${mosip.certify.cache.security.secretkey.reference-id}")
private String cacheSecretKeyRefId;

@Value("${mosip.certify.vciplugin.sunbird-rc.enable-psut-based-registry-search:false}")
private boolean enablePSUTBasedRegistrySearch;

@Value("${mosip.esignet.authenticator.credissuer.bearer-token}")
private String credIssuerBeaerToken;

@Value("${mosip.certify.cache.security.algorithm-name}")
private String aesECBTransformation;

@Value("#{'${mosip.certify.vciplugin.sunbird-rc.supported-credential-types}'.split(',')}")
List<String> supportedCredentialTypes;

Expand All @@ -100,6 +150,12 @@ public class SunbirdRCVCIssuancePlugin implements VCIssuancePlugin {

private VelocityEngine vEngine;

@Autowired
CacheManager cacheManager;
@Value("${mosip.esignet.ida.vci-user-info-cache}")
private String userinfoCache;
private static final String ACCESS_TOKEN_HASH = "accessTokenHash";


@PostConstruct
public void initialize() throws VCIExchangeException {
Expand All @@ -121,57 +177,108 @@ public InputStream getResourceStream(String name) throws ResourceNotFoundExcepti
vEngine.init();
//Validate all the supported VC
for (String credentialType : supportedCredentialTypes) {
validateAndCachePropertiesForCredentialType(credentialType.trim());
//validateAndCachePropertiesForCredentialType(credentialType.trim());
}
}

@Override
public VCResult<JsonLDObject> getVerifiableCredentialWithLinkedDataProof(VCRequestDto vcRequestDto, String holderId, Map<String, Object> identityDetails) throws VCIExchangeException {
if (vcRequestDto == null || vcRequestDto.getType() == null) {
throw new VCIExchangeException(ErrorConstants.VCI_EXCHANGE_FAILED);
public VCResult<JsonLDObject> getVerifiableCredentialWithLinkedDataProof(VCRequestDto vcRequestDto, String holderId,
Map<String, Object> identityDetails) throws VCIExchangeException {
JsonLDObject vcJsonLdObject = null;
String individualId = null;
try {
OIDCTransaction transaction = getOAuthTransaction(identityDetails.get(ACCESS_TOKEN_HASH).toString());
individualId = getIndividualId(transaction.getIndividualId());
System.out.println("individualId : "+individualId);
} catch (Exception e) {
throw new RuntimeException(e);
}
List<String> types = vcRequestDto.getType();
if (types.isEmpty() || !types.get(0).equals("VerifiableCredential")) {
log.error("Invalid request: first item in type is not VerifiableCredential");
throw new VCIExchangeException(ErrorConstants.VCI_EXCHANGE_FAILED);
try {
VCResult vcResult = new VCResult();
Map<String,Object> vcResponseMap = fetchCredential(getCredentialUrl + individualId);
vcJsonLdObject = JsonLDObject.fromJsonObject((Map<String, Object>)vcResponseMap.get(CREDENTIAL_OBJECT_KEY));
vcResult.setCredential(vcJsonLdObject);
vcResult.setFormat("ldp_vc");
return vcResult;
} catch (Exception e) {
log.error("Failed to build credissuer response", e);
}
types.remove(0);
String requestedCredentialType = String.join("-", types);
//Check if the key is in the supported-credential-types
if (!supportedCredentialTypes.contains(requestedCredentialType)) {
log.error("Credential type is not supported");
throw new VCIExchangeException();
}

private Map<String,Object> fetchCredential(String entityUrl) throws VCIExchangeException {
RequestEntity<Void> requestEntity = RequestEntity
.get(UriComponentsBuilder.fromUriString(entityUrl).build().toUri())
.header("Authorization", "Bearer " + credIssuerBeaerToken) // Set the headers
.build();
ResponseEntity<Map<String,Object>> responseEntity = restTemplate.exchange(requestEntity,
new ParameterizedTypeReference<Map<String,Object>>() {});
if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) {
return responseEntity.getBody();
}else {
log.error("Credissuer service is not running. Status Code: " , responseEntity.getStatusCode());
throw new VCIExchangeException(ErrorConstants.VCI_EXCHANGE_FAILED);
}
//Validate context of vcrequestdto with template
List<String> contextList=vcRequestDto.getContext();
for(String supportedType:supportedCredentialTypes){
Template template= credentialTypeTemplates.get(supportedType);
validateContextUrl(template,contextList);
}

@SuppressWarnings("unchecked")
public OIDCTransaction getOAuthTransaction(String accessTokenHash) throws Exception {
if (cacheManager.getCache(userinfoCache) != null) {
try {
OIDCTransaction oIDCTransaction = cacheManager.getCache(userinfoCache).get(accessTokenHash, OIDCTransaction.class); //NOSONAR getCache() will not be returning null here.
return oIDCTransaction;
} catch (Exception e) {
log.error("Exception occured while fetching the cache", e);
throw new Exception(e);
}

}
throw new Exception("cache_missing>>>>>");
}

String registrySearchField = (identityDetails.containsKey("sub")) ? (String) identityDetails.get("sub") : null;
if (registrySearchField == null) {
log.error("Invalid request: registrySearchField is null");
throw new VCIExchangeException(ErrorConstants.VCI_EXCHANGE_FAILED);
protected String getIndividualId(String encryptedIndividualId) throws Exception {
if (!storeIndividualId)
return null;
return secureIndividualId ? decryptIndividualId(encryptedIndividualId) : encryptedIndividualId;
}

private String decryptIndividualId(String encryptedIndividualId) throws Exception {
try {
Cipher cipher = Cipher.getInstance(aesECBTransformation);
byte[] decodedBytes = b64Decode(encryptedIndividualId);
cipher.init(Cipher.DECRYPT_MODE, getSecretKeyFromHSM());
return new String(cipher.doFinal(decodedBytes, 0, decodedBytes.length));
} catch (Exception e) {
log.error("Error Cipher Operations of provided secret data.", e);
throw new Exception(AES_CIPHER_FAILED);
}
Map<String,Object> responseRegistryMap;
if(enablePSUTBasedRegistrySearch){
String registrySearchUrl=credentialTypeConfigMap.get(requestedCredentialType).get(REGISTRY_SEARCH_URL);
responseRegistryMap= fetchRegistryObjectByPSUT(registrySearchUrl,registrySearchField);
}else {
String registryUrl=credentialTypeConfigMap.get(requestedCredentialType).get(REGISTRY_GET_URL);
responseRegistryMap =fetchRegistryObject(registryUrl+ registrySearchField);
}

private Key getSecretKeyFromHSM() throws Exception {
String keyAlias = getKeyAlias(OIDC_SERVICE_APP_ID, cacheSecretKeyRefId);
if (Objects.nonNull(keyAlias)) {
return keyStore.getSymmetricKey(keyAlias);
}
Map<String,Object> credentialRequestMap = createCredentialIssueRequest(requestedCredentialType, responseRegistryMap,vcRequestDto,holderId);
Map<String,Object> vcResponseMap =sendCredentialIssueRequest(credentialRequestMap);

VCResult vcResult = new VCResult();
JsonLDObject vcJsonLdObject = JsonLDObject.fromJsonObject((Map<String, Object>)vcResponseMap.get(CREDENTIAL_OBJECT_KEY));
vcResult.setCredential(vcJsonLdObject);
vcResult.setFormat(LINKED_DATA_PROOF_VC_FORMAT);
return vcResult;
throw new Exception(NO_UNIQUE_ALIAS);
}

private String getKeyAlias(String keyAppId, String keyRefId) throws Exception {
Map<String, List<KeyAlias>> keyAliasMap = dbHelper.getKeyAliases(keyAppId, keyRefId,
LocalDateTime.now(ZoneOffset.UTC));
List<KeyAlias> currentKeyAliases = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS);
if (!currentKeyAliases.isEmpty() && currentKeyAliases.size() == 1) {
return currentKeyAliases.get(0).getAlias();
}
log.error("CurrentKeyAlias is not unique. KeyAlias count: {}", currentKeyAliases.size());
throw new Exception(NO_UNIQUE_ALIAS);
}



private byte[] b64Decode(String value) {
return urlSafeDecoder.decode(value);
};

@Override
public VCResult<String> getVerifiableCredential(VCRequestDto vcRequestDto, String holderId, Map<String, Object> identityDetails) throws VCIExchangeException {
throw new VCIExchangeException(ErrorConstants.NOT_IMPLEMENTED);
Expand Down