Skip to content

Commit

Permalink
[INJIVER-587] - code cleanup
Browse files Browse the repository at this point in the history
Signed-off-by: Sreenadh S <[email protected]>
  • Loading branch information
sree96 committed Nov 27, 2024
1 parent 7bf608b commit db67f41
Show file tree
Hide file tree
Showing 13 changed files with 68 additions and 42 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.mosip.verifycore.dto.authorizationRequest;

import io.mosip.verifycore.models.PresentationDefinition;
import io.mosip.verifycore.shared.Constants;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -15,7 +16,7 @@
@NoArgsConstructor(force = true)
public class AuthorizationRequestDto implements Serializable {

private final String responseType = "vp_token";
private final String responseType = Constants.RESPONSE_TYPE;
private final String clientId;
private final String presentationDefinitionUri;
private String responseUri;
Expand All @@ -24,7 +25,7 @@ public class AuthorizationRequestDto implements Serializable {

public AuthorizationRequestDto(String clientId, PresentationDefinition presentationDefinition,String nonce) {
this.clientId = clientId;
this.responseUri = "/vp-direct-post";
this.responseUri = Constants.RESPONSE_SUBMISSION_URI;
this.presentationDefinitionUri = presentationDefinition.getURL();
this.iat = Instant.now().toEpochMilli();
this.nonce = nonce;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.mosip.verifycore.dto.submission;

import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
Expand All @@ -13,10 +12,8 @@
@Builder
public class VpSubmissionDto {
@NotNull
@JsonProperty("vp_token")
String vpToken;
@NotNull
@JsonProperty("presentation_submission")
PresentationSubmissionDto presentationSubmission;
@NotNull
String state;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package io.mosip.verifycore.exception;

public class VerificationFailedException extends Exception{
private static final String message = "Verification Failed";
public VerificationFailedException() {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.mosip.verifycore.dto.presentation.InputDescriptorDto;
import io.mosip.verifycore.dto.presentation.SubmissionRequirementDto;
import io.mosip.verifycore.shared.Constants;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
Expand All @@ -12,7 +13,6 @@
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.net.URI;
import java.util.List;

@Table(name = "presentations")
Expand All @@ -35,6 +35,6 @@ public class PresentationDefinition {


public String getURL(){
return "/vp-definition/"+this.id;
return Constants.VP_DEFINITION_URI +this.id;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package io.mosip.verifycore.shared;

public class Config {
public static int DEFAULT_EXPIRY = 300;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
package io.mosip.verifycore.shared;

public class Constants {
public static int DEFAULT_EXPIRY = 300;
public static final String RESPONSE_SUBMISSION_URI = "/vp-direct-post";
public static final String VP_DEFINITION_URI = "/vp-definition/";
public static final String RESPONSE_TYPE = "vp_token";

public static final String PUBLIC_KEY_HEADER = "-----BEGIN PUBLIC KEY-----";
public static final String PUBLIC_KEY_FOOTER = "-----END PUBLIC KEY-----";
public static final String TRANSACTION_ID_PREFIX = "txn";
public static final String REQUEST_ID_PREFIX = "req";
public static final String VC_EXPIRED_ERROR_CODE = "ERR_VC_EXPIRED";

//JSON KEYS
public static final String KEY_PROOF = "proof";
public static final String KEY_JWS = "jws";
public static final String KEY_VERIFICATION_METHOD = "verificationMethod";
public static final String KEY_VERIFIABLE_CREDENTIAL = "verifiableCredential";
public static final String KEY_CREDENTIAL = "credential";


}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import io.mosip.verifycore.enums.Status;

public interface VerifiablePresentationRequestService {
AuthorizationRequestCreateResponseDto createAuthorizationRequest(AuthorizationRequestCreateDto vpRequestCreate, String serverURL);
AuthorizationRequestCreateResponseDto createAuthorizationRequest(AuthorizationRequestCreateDto vpRequestCreate);
Status getStatusFor(String requestId);
String getTransactionIdFor(String requestId);
String getStatusForRequestIdFor(String transactionId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.mosip.verifycore.utils;

import io.mosip.verifycore.shared.Constants;
import org.apache.tomcat.util.codec.binary.Base64;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
Expand All @@ -19,7 +20,12 @@ public static String generateNonce()

public static RSAPublicKey getPublicKeyFromString(String pem) {
String publicKeyPEM = pem;
publicKeyPEM = publicKeyPEM.replace("\n", "").replace("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");

publicKeyPEM = publicKeyPEM
.replace("\n", "")
.replace("\\n", "")
.replace(Constants.PUBLIC_KEY_HEADER, "")
.replace(Constants.PUBLIC_KEY_FOOTER, "");
byte[] encoded = java.util.Base64.getDecoder().decode(publicKeyPEM);
KeyFactory kf = null;
try {
Expand All @@ -35,7 +41,10 @@ public static RSAPublicKey getPublicKeyFromString(String pem) {
}

public static String getFormattedJws(String jws){
return jws.replace("\\n","").replace("\n","").replace("==","");
return jws
.replace("\\n","")
.replace("\n","")
.replace("==","");
}

}
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
package io.mosip.verifycore.utils;

import jakarta.servlet.http.HttpServletRequest;
import java.util.UUID;

public class Utils {
public static String createID(String prefix){
return prefix+"_"+UUID.randomUUID();
}

public static String getServerAddress(HttpServletRequest request) {
return request.getRequestURL().toString().replaceAll(request.getServletPath(),"");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import io.mosip.verifycore.dto.authorizationRequest.StatusResponseDto;
import io.mosip.verifycore.enums.Status;
import io.mosip.verifycore.spi.VerifiablePresentationRequestService;
import io.mosip.verifycore.utils.Utils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
Expand All @@ -23,16 +21,11 @@ public class VpRequestController {
VerifiablePresentationRequestService verifiablePresentationRequestService;

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AuthorizationRequestCreateResponseDto> createVpRequest(@Valid @RequestBody AuthorizationRequestCreateDto vpRequestCreate, HttpServletRequest request) {
public ResponseEntity<AuthorizationRequestCreateResponseDto> createVpRequest(@Valid @RequestBody AuthorizationRequestCreateDto vpRequestCreate) {
if (vpRequestCreate.getPresentationDefinition() == null && vpRequestCreate.getVerificationType() == null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
// if (vpRequestCreate.verificationType()!=null)
// // create a definition
// PresentationDefinition presentationDefinition = presentationDefinitionService.getPresentationDefinition(vpRequestCreate.verificationType());
// //create auth REQ
//else
if (vpRequestCreate.getPresentationDefinition() != null) {
AuthorizationRequestCreateResponseDto authorizationRequestResponse = verifiablePresentationRequestService.createAuthorizationRequest(vpRequestCreate, Utils.getServerAddress(request));
AuthorizationRequestCreateResponseDto authorizationRequestResponse = verifiablePresentationRequestService.createAuthorizationRequest(vpRequestCreate);
return new ResponseEntity<>(authorizationRequestResponse, HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.mosip.verifycore.dto.submission.VpSubmissionResponseDto;
import io.mosip.verifycore.enums.Status;
import io.mosip.verifycore.models.VpSubmission;
import io.mosip.verifycore.shared.Constants;
import io.mosip.verifycore.spi.VerifiablePresentationRequestService;
import io.mosip.verifycore.spi.VerifiablePresentationSubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -41,7 +42,7 @@ public ResponseEntity<SubmissionResultDto> getVpResult(@PathVariable String tran
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}

@PostMapping(path = "/vp-direct-post", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@PostMapping(path = Constants.RESPONSE_SUBMISSION_URI, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<VpSubmissionResponseDto> submitVp(@RequestParam(value = "vp_token") String vpToken, @RequestParam(value = "presentation_submission") String presentationSubmission, @RequestParam(value = "state") String state) {
PresentationSubmissionDto presentationSubmissionDto = new Gson().fromJson(presentationSubmission, PresentationSubmissionDto.class);
VpSubmissionDto vpSubmissionDto = new VpSubmissionDto(vpToken, presentationSubmissionDto, state);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.mosip.verifycore.enums.Status;
import io.mosip.verifycore.models.AuthorizationRequestCreateResponse;
import io.mosip.verifycore.models.PresentationDefinition;
import io.mosip.verifycore.shared.Constants;
import io.mosip.verifycore.spi.VerifiablePresentationRequestService;
import io.mosip.verifycore.utils.SecurityUtils;
import io.mosip.verifycore.utils.Utils;
Expand All @@ -16,7 +17,7 @@
import org.springframework.stereotype.Service;
import java.time.Instant;

import static io.mosip.verifycore.shared.Constants.DEFAULT_EXPIRY;
import static io.mosip.verifycore.shared.Config.DEFAULT_EXPIRY;

@Service
public class VerifiablePresentationRequestServiceImpl implements VerifiablePresentationRequestService {
Expand All @@ -28,11 +29,10 @@ public class VerifiablePresentationRequestServiceImpl implements VerifiablePrese
public VerifiablePresentationRequestServiceImpl() {}

@Override
public AuthorizationRequestCreateResponseDto createAuthorizationRequest(AuthorizationRequestCreateDto vpRequestCreate, String serverURL) {
public AuthorizationRequestCreateResponseDto createAuthorizationRequest(AuthorizationRequestCreateDto vpRequestCreate) {

//TODO : constants
String transactionId = vpRequestCreate.getTransactionId()!=null ? vpRequestCreate.getTransactionId() : Utils.createID("txn");
String requestId = Utils.createID("req");
String transactionId = vpRequestCreate.getTransactionId()!=null ? vpRequestCreate.getTransactionId() : Utils.createID(Constants.TRANSACTION_ID_PREFIX);
String requestId = Utils.createID(Constants.REQUEST_ID_PREFIX);
long expiresAt = Instant.now().plusSeconds(DEFAULT_EXPIRY).toEpochMilli();
String nonce = vpRequestCreate.getNonce()!=null ? vpRequestCreate.getNonce() : SecurityUtils.generateNonce();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
import io.mosip.verifycore.dto.submission.VpSubmissionResponseDto;
import io.mosip.verifycore.enums.Status;
import io.mosip.verifycore.enums.VerificationStatus;
import io.mosip.verifycore.exception.VerificationFailedException;
import io.mosip.verifycore.models.VpSubmission;
import io.mosip.verifycore.shared.Constants;
import io.mosip.verifycore.spi.VerifiablePresentationSubmissionService;
import io.mosip.verifyservice.repository.AuthorizationRequestCreateResponseRepository;
import io.mosip.verifyservice.repository.VpSubmissionRepository;
Expand All @@ -36,22 +38,20 @@ public class VerifiablePresentationSubmissionServiceImpl implements VerifiablePr

@Override
public VpSubmissionResponseDto submit(VpSubmissionDto vpSubmissionDto) {
String jws = getFormattedJws(new JSONObject(vpSubmissionDto.getVpToken()).getJSONObject("proof").getString("jws"));
String publicKeyPem = new JSONObject(vpSubmissionDto.getVpToken()).getJSONObject("proof").getString("verificationMethod");
JSONObject vpProof = new JSONObject(vpSubmissionDto.getVpToken()).getJSONObject(Constants.KEY_PROOF);
String jws = getFormattedJws(vpProof.getString(Constants.KEY_JWS));
String publicKeyPem = vpProof.getString(Constants.KEY_VERIFICATION_METHOD);

//TODO: Dynamic algo type
//TODO: try catch for key exceptions and failure scenario
try {
// getJwsAlgorithm(jws,publicKeyPem);
Algorithm algorithm = Algorithm.RSA256(getPublicKeyFromString(publicKeyPem), null);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(jws);

//verify vc
JSONArray verifiableCredentials = new JSONObject(vpSubmissionDto.getVpToken()).getJSONArray("verifiableCredential");
JSONArray verifiableCredentials = new JSONObject(vpSubmissionDto.getVpToken()).getJSONArray(Constants.KEY_VERIFIABLE_CREDENTIAL);
List<VerificationResult> verificationResults = new ArrayList<>();
for (Object verifiableCredential : verifiableCredentials) {
JSONObject credential = new JSONObject((String) verifiableCredential).getJSONObject("verifiableCredential").getJSONObject("credential");
JSONObject credential = new JSONObject((String) verifiableCredential).getJSONObject(Constants.KEY_VERIFIABLE_CREDENTIAL).getJSONObject(Constants.KEY_CREDENTIAL);
VerificationResult singleVcVerification = new CredentialsVerifier().verify(credential.toString(), CredentialFormat.LDP_VC);
System.out.println(singleVcVerification);
verificationResults.add(singleVcVerification);
Expand All @@ -60,15 +60,15 @@ public VpSubmissionResponseDto submit(VpSubmissionDto vpSubmissionDto) {
boolean anyVcExpired = false;
for (VerificationResult verificationResult : verificationResults) {
combinedVerificationStatus = combinedVerificationStatus && verificationResult.getVerificationStatus();
anyVcExpired = anyVcExpired || verificationResult.getVerificationErrorCode().equals("ERR_VC_EXPIRED");
anyVcExpired = anyVcExpired || verificationResult.getVerificationErrorCode().equals(Constants.VC_EXPIRED_ERROR_CODE);
}
if (!combinedVerificationStatus) {
throw new Exception("Verification Failed");
throw new VerificationFailedException();
}
if (anyVcExpired) {
vpSubmissionRepository.save(new VpSubmission(vpSubmissionDto.getState(), vpSubmissionDto.getVpToken(), vpSubmissionDto.getPresentationSubmission(),VerificationStatus.EXPIRED ));
vpSubmissionRepository.save(new VpSubmission(vpSubmissionDto.getState(), vpSubmissionDto.getVpToken(), vpSubmissionDto.getPresentationSubmission(),VerificationStatus.EXPIRED));
}else {
vpSubmissionRepository.save(new VpSubmission(vpSubmissionDto.getState(), vpSubmissionDto.getVpToken(), vpSubmissionDto.getPresentationSubmission(),VerificationStatus.SUCCESS ));
vpSubmissionRepository.save(new VpSubmission(vpSubmissionDto.getState(), vpSubmissionDto.getVpToken(), vpSubmissionDto.getPresentationSubmission(),VerificationStatus.SUCCESS));
}

} catch (Exception e) {
Expand Down

0 comments on commit db67f41

Please sign in to comment.