Skip to content

Commit

Permalink
fix: add exceptions and fix naming
Browse files Browse the repository at this point in the history
  • Loading branch information
mustafasalfiti authored and nitin-vavdiya committed May 14, 2024
1 parent 4aec527 commit 531d3f7
Show file tree
Hide file tree
Showing 14 changed files with 93 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,21 @@
@Repository
public interface WalletKeyRepository extends BaseRepository<WalletKey, Long> {
/**
* Gets by wallet id.
* Gets by wallet id and algorithm.
*
* @param id the id
* param algorithm the algorithm
* @return the by wallet id
*/
WalletKey getByWalletIdAndAlgorithm(Long id, String algorithm);

/**
* Gets by wallet id.
* @param id
* @return WalletKey
*/
WalletKey getByWalletId(Long id);

WalletKey findFirstByWallet_Bpn(String bpn);

WalletKey findFirstByWallet_Did(String did);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public CredentialsResponse issueCredential(Map<String, Object> data, boolean asJ
Validate.isFalse(callerBpn.equals(issuerWallet.getBpn())).launch(new ForbiddenException(BASE_WALLET_BPN_IS_NOT_MATCHING_WITH_REQUEST_BPN_FROM_TOKEN));

// get Key
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdentifierAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());

// check if the expiryDate is set
Date expiryDate = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public PageImpl<CredentialsResponse> getCredentials(GetCredentialsCommand comman
*/
@Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
public VerifiableCredential issueBpnCredential(Wallet baseWallet, Wallet holderWallet, boolean authority) {
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdentifierAsBytes(baseWallet.getId(), baseWallet.getAlgorithm());
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdAsBytes(baseWallet.getId(), baseWallet.getAlgorithm());
List<String> types = List.of(VerifiableCredentialType.VERIFIABLE_CREDENTIAL, MIWVerifiableCredentialType.BPN_CREDENTIAL);
VerifiableCredentialSubject verifiableCredentialSubject = new VerifiableCredentialSubject(Map.of(StringPool.TYPE, MIWVerifiableCredentialType.BPN_CREDENTIAL,
StringPool.ID, holderWallet.getDid(),
Expand Down Expand Up @@ -233,7 +233,7 @@ public CredentialsResponse issueFrameworkCredential(IssueFrameworkCredentialRequ

validateAccess(callerBPN, baseWallet);
// get Key
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdentifierAsBytes(baseWallet.getId(), baseWallet.getAlgorithm());
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdAsBytes(baseWallet.getId(), baseWallet.getAlgorithm());

//if base wallet issue credentials to itself
boolean isSelfIssued = isSelfIssued(holderWallet.getBpn());
Expand Down Expand Up @@ -293,7 +293,7 @@ public CredentialsResponse issueDismantlerCredential(IssueDismantlerCredentialRe
//check duplicate
isCredentialExit(holderWallet.getDid(), MIWVerifiableCredentialType.DISMANTLER_CREDENTIAL);

byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdentifierAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());

//if base wallet issue credentials to itself
boolean isSelfIssued = isSelfIssued(request.getBpn());
Expand Down Expand Up @@ -352,7 +352,7 @@ public CredentialsResponse issueMembershipCredential(IssueMembershipCredentialRe

validateAccess(callerBPN, issuerWallet);

byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdentifierAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());
List<String> types = List.of(VerifiableCredentialType.VERIFIABLE_CREDENTIAL, VerifiableCredentialType.MEMBERSHIP_CREDENTIAL);

//if base wallet issue credentials to itself
Expand Down Expand Up @@ -417,7 +417,7 @@ public CredentialsResponse issueCredentialUsingBaseWallet(String holderDid, Map<
validateAccess(callerBpn, issuerWallet);

// get issuer Key
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdentifierAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());
byte[] privateKeyBytes = walletKeyService.getPrivateKeyByWalletIdAsBytes(issuerWallet.getId(), issuerWallet.getAlgorithm());

boolean isSelfIssued = isSelfIssued(holderWallet.getBpn());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,8 @@ public Map<String, Object> createPresentation(Map<String, Object> data, boolean
return buildVP(asJwt, audience, callerBpn, callerWallet, verifiableCredentials, SupportedAlgorithms.ED25519);
}

@SneakyThrows({ InvalidePrivateKeyFormat.class })
private Map<String, Object> buildVP(boolean asJwt, String audience, String callerBpn, Wallet callerWallet,
List<VerifiableCredential> verifiableCredentials, SupportedAlgorithms algorithm) {
List<VerifiableCredential> verifiableCredentials, SupportedAlgorithms algorithm){
Map<String, Object> response = new HashMap<>();
if (asJwt && algorithm.equals(SupportedAlgorithms.ES256K)) {
buildVPJwtES256K(audience, callerBpn, callerWallet, verifiableCredentials, algorithm, response);
Expand All @@ -174,15 +173,16 @@ private void buildVPJsonLd(String callerBpn, List<VerifiableCredential> verifiab
response.put(StringPool.VP, verifiablePresentation);
}

private void buildVPJwtEdDSA(String audience, String callerBpn, Wallet callerWallet, List<VerifiableCredential> verifiableCredentials, SupportedAlgorithms algorithm, Map<String, Object> response) throws InvalidePrivateKeyFormat {
@SneakyThrows({ InvalidPrivateKeyFormatException.class})
private void buildVPJwtEdDSA(String audience, String callerBpn, Wallet callerWallet, List<VerifiableCredential> verifiableCredentials, SupportedAlgorithms algorithm, Map<String, Object> response) {
Pair<Did, Object> result = getPrivateKey(callerWallet, algorithm, audience, callerBpn);

SerializedJwtPresentationFactory presentationFactory = new SerializedJwtPresentationFactoryImpl(
new SignedJwtFactory(new OctetKeyPairFactory()), new JsonLdSerializerImpl(), result.getKey());

x21559PrivateKey ed25519Key = (x21559PrivateKey) result.getRight();
x21559PrivateKey privateKey = new x21559PrivateKey(ed25519Key.asByte());
SignedJWT presentation = presentationFactory.createPresentation(result.getLeft(), verifiableCredentials, audience, privateKey);
x25519PrivateKey ed25519Key = (x25519PrivateKey) result.getRight();
x25519PrivateKey privateKey = new x25519PrivateKey(ed25519Key.asByte());
SignedJWT presentation = presentationFactory.createPresentation(result.getLeft(), verifiableCredentials, audience, privateKey , "keyId" );

response.put(StringPool.VP, presentation.serialize());
}
Expand All @@ -197,6 +197,7 @@ private void buildVPJwtES256K(String audience, String callerBpn, Wallet callerWa
response.put(StringPool.VP, presentation.serialize());
}

@SneakyThrows({ DidParseException.class })
private Pair<Did, Object> getPrivateKey(Wallet callerWallet, SupportedAlgorithms algorithm, String audience, String callerBpn) {
log.debug("Creating VP as JWT for bpn ->{}", callerBpn);
Validate.isFalse(StringUtils.hasText(audience)).launch(new BadDataException("Audience needed to create VP as JWT"));
Expand All @@ -205,7 +206,7 @@ private Pair<Did, Object> getPrivateKey(Wallet callerWallet, SupportedAlgorithms
Did vpIssuerDid = DidParser.parse(callerWallet.getDid());

//Build JWT
return Pair.of(vpIssuerDid, walletKeyService.getPrivateKeyByWalletIdentifierAndAlgorithm(callerWallet.getId(), algorithm));
return Pair.of(vpIssuerDid, walletKeyService.getPrivateKeyByWalletIdAndAlgorithm(callerWallet.getId(), algorithm));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,14 @@ protected SpecificationUtil<WalletKey> getSpecificationUtil() {
* Get private key by wallet identifier as bytes byte [ ].
*
* @param walletId the wallet id
* @param algorithm the algorithm
* @return the byte [ ]
*/
@SneakyThrows
public byte[] getPrivateKeyByWalletIdentifierAsBytes(long walletId, String algorithm) {
Object privateKey = getPrivateKeyByWalletIdentifierAndAlgorithm(walletId, SupportedAlgorithms.valueOf(algorithm));
if (privateKey instanceof x21559PrivateKey x21559PrivateKey) {
return x21559PrivateKey.asByte();
public byte[] getPrivateKeyByWalletIdAsBytes(long walletId, String algorithm) {
Object privateKey = getPrivateKeyByWalletIdAndAlgorithm(walletId, SupportedAlgorithms.valueOf(algorithm));
if (privateKey instanceof x25519PrivateKey x25519PrivateKey) {
return x25519PrivateKey.asByte();
} else {
return ((ECPrivateKey) privateKey).getEncoded();
}
Expand All @@ -85,16 +86,16 @@ public byte[] getPrivateKeyByWalletIdentifierAsBytes(long walletId, String algor
* Gets private key by wallet identifier.
*
* @param walletId the wallet id
* @param algorithm the algorithm
* @return the private key by wallet identifier
*/
@SneakyThrows

public Object getPrivateKeyByWalletIdentifierAndAlgorithm(long walletId, SupportedAlgorithms algorithm) {
public Object getPrivateKeyByWalletIdAndAlgorithm(long walletId, SupportedAlgorithms algorithm) {
WalletKey wallet = walletKeyRepository.getByWalletIdAndAlgorithm(walletId, algorithm.toString());
String privateKey = encryptionUtils.decrypt(wallet.getPrivateKey());
byte[] content = new PemReader(new StringReader(privateKey)).readPemObject().getContent();
if (SupportedAlgorithms.ED25519.equals(algorithm)) {
return new x21559PrivateKey(content);
return new x25519PrivateKey(content);
} else if (SupportedAlgorithms.ES256K.equals(algorithm)) {
KeyFactory kf = KeyFactory.getInstance(EC);
return kf.generatePrivate(new PKCS8EncodedKeySpec(content));
Expand All @@ -103,4 +104,16 @@ public Object getPrivateKeyByWalletIdentifierAndAlgorithm(long walletId, Support
}
}

/**
* Gets wallet key by wallet identifier.
*
* @param walletId the wallet id
* @return the wallet key by wallet identifier
*/
@SneakyThrows
public String getWalletKeyIdByWalletId(long walletId) {
return walletKeyRepository.getByWalletId(walletId).getKeyId();
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.eclipse.tractusx.managedidentitywallets.constant.StringPool;
import org.eclipse.tractusx.managedidentitywallets.constant.SupportedAlgorithms;
import org.eclipse.tractusx.managedidentitywallets.dao.entity.HoldersCredential;
import org.eclipse.tractusx.managedidentitywallets.dto.SecureTokenRequest;
import org.eclipse.tractusx.managedidentitywallets.dao.entity.Wallet;
Expand All @@ -35,6 +36,7 @@
import org.eclipse.tractusx.managedidentitywallets.service.WalletKeyService;
import org.eclipse.tractusx.ssi.lib.crypt.octet.OctetKeyPairFactory;
import org.eclipse.tractusx.ssi.lib.crypt.x25519.x25519PrivateKey;
import org.eclipse.tractusx.ssi.lib.exception.did.DidParseException;
import org.eclipse.tractusx.ssi.lib.exception.json.TransformJsonLdException;
import org.eclipse.tractusx.ssi.lib.exception.key.InvalidPrivateKeyFormatException;
import org.eclipse.tractusx.ssi.lib.exception.proof.SignatureGenerateFailedException;
Expand Down Expand Up @@ -182,7 +184,8 @@ public static SecureTokenRequest getSecureTokenRequest(MultiValueMap<String, Str
return objectMapper.convertValue(singleValueMap, SecureTokenRequest.class);
}

public static String vcAsJwt(Wallet issuerWallet, Wallet holderWallet, VerifiableCredential vc , WalletKeyService walletKeyService) {
@SneakyThrows({DidParseException.class})
public static String vcAsJwt(Wallet issuerWallet, Wallet holderWallet, VerifiableCredential vc , WalletKeyService walletKeyService){

Did issuerDid = DidParser.parse(issuerWallet.getDid());
Did holderDid = DidParser.parse(holderWallet.getDid());
Expand All @@ -191,13 +194,14 @@ public static String vcAsJwt(Wallet issuerWallet, Wallet holderWallet, Verifiabl
SerializedJwtVCFactoryImpl vcFactory = new SerializedJwtVCFactoryImpl(
new SignedJwtFactory(new OctetKeyPairFactory()));

x25519PrivateKey privateKey = walletKeyService.getPrivateKeyByWalletId(issuerWallet.getId());
x25519PrivateKey privateKey = (x25519PrivateKey) walletKeyService.getPrivateKeyByWalletIdAndAlgorithm(issuerWallet.getId(), SupportedAlgorithms.ED25519);
// JWT Factory

SignedJWT vcJWT = vcFactory.createVCJwt(issuerDid, holderDid, vc,
privateKey,
walletKeyService.getWalletKeyIdByWalletId(issuerWallet.getId()));

walletKeyService.getWalletKeyIdByWalletId(issuerWallet.getId())

);
return vcJWT.serialize();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.eclipse.tractusx.managedidentitywallets.config.MIWSettings;
import org.eclipse.tractusx.managedidentitywallets.constant.MIWVerifiableCredentialType;
import org.eclipse.tractusx.managedidentitywallets.constant.StringPool;
import org.eclipse.tractusx.managedidentitywallets.constant.SupportedAlgorithms;
import org.eclipse.tractusx.managedidentitywallets.dao.entity.HoldersCredential;
import org.eclipse.tractusx.managedidentitywallets.dao.entity.IssuersCredential;
import org.eclipse.tractusx.managedidentitywallets.dao.entity.Wallet;
Expand Down Expand Up @@ -175,7 +176,7 @@ void shouldIssueCredentialAsJwt()
when(walletKey.getKeyId()).thenReturn(KEY_ID);
when(walletKey.getId()).thenReturn(42L);

when(walletKeyService.getPrivateKeyByWalletId(baseWallet.getId()))
when(walletKeyService.getPrivateKeyByWalletIdAndAlgorithm(baseWallet.getId() ,SupportedAlgorithms.valueOf(baseWallet.getAlgorithm())))
.thenReturn(new x25519PrivateKey(keyPair.getPrivateKey().asStringForStoring(), true));
when(walletKeyService.getWalletKeyIdByWalletId(baseWallet.getId())).thenReturn(walletKeyId);

Expand Down Expand Up @@ -225,7 +226,7 @@ void shouldIssueCredentialAsJwt()
when(walletKey.getKeyId()).thenReturn(KEY_ID);
when(walletKey.getId()).thenReturn(42L);

when(walletKeyService.getPrivateKeyByWalletId(baseWallet.getId()))
when(walletKeyService.getPrivateKeyByWalletIdAndAlgorithm(baseWallet.getId() ,SupportedAlgorithms.valueOf(baseWallet.getAlgorithm())))
.thenReturn(new x25519PrivateKey(keyPair.getPrivateKey().asStringForStoring(), true));
when(walletKeyService.getWalletKeyIdByWalletId(baseWallet.getId())).thenReturn(walletKeyId);

Expand Down Expand Up @@ -264,7 +265,7 @@ void shouldIssueCredentialAsJwt() throws IOException, InvalidPrivateKeyFormatExc
when(walletKey.getKeyId()).thenReturn(KEY_ID);
when(walletKey.getId()).thenReturn(42L);

when(walletKeyService.getPrivateKeyByWalletId(baseWallet.getId()))
when(walletKeyService.getPrivateKeyByWalletIdAndAlgorithm(baseWallet.getId() ,SupportedAlgorithms.valueOf(baseWallet.getAlgorithm())))
.thenReturn(new x25519PrivateKey(keyPair.getPrivateKey().asStringForStoring(), true));
when(walletKeyService.getWalletKeyIdByWalletId(baseWallet.getId())).thenReturn(walletKeyId);

Expand Down Expand Up @@ -298,7 +299,7 @@ void shouldIssueCredentialAsJwt() throws IOException, ParseException, InvalidPri
MockUtil.generateDid("basewallet")).build();

MockUtil.makeCreateWorkForIssuer(issuersCredentialRepository);
when(walletKeyService.getPrivateKeyByWalletIdAsBytes(any(Long.class))).thenReturn(keyPair.getPrivateKey()
when(walletKeyService.getPrivateKeyByWalletIdAsBytes(any(Long.class) , SupportedAlgorithms.ED25519.toString())).thenReturn(keyPair.getPrivateKey()
.asByte());
when(commonService.getWalletByIdentifier(holderWalletBpn)).thenReturn(holderWallet);
when(commonService.getWalletByIdentifier(verifiableCredential.getIssuer()
Expand All @@ -317,7 +318,7 @@ public HoldersCredential answer(InvocationOnMock invocation) throws Throwable {
WalletKey walletKey = mock(WalletKey.class);
when(walletKey.getKeyId()).thenReturn(KEY_ID);
when(walletKey.getId()).thenReturn(42L);
when(walletKeyService.getPrivateKeyByWalletId(baseWallet.getId()))
when(walletKeyService.getPrivateKeyByWalletIdAndAlgorithm(baseWallet.getId() ,SupportedAlgorithms.valueOf(baseWallet.getAlgorithm())))
.thenReturn(new x25519PrivateKey(keyPair.getPrivateKey().asStringForStoring(), true));
when(walletKeyService.getWalletKeyIdByWalletId(baseWallet.getId())).thenReturn(walletKeyId);

Expand Down Expand Up @@ -431,7 +432,7 @@ private void mockCommon(
when(miwSettings.authorityWalletBpn()).thenReturn(baseWalletBpn);
when(commonService.getWalletByIdentifier(baseWalletBpn)).thenReturn(baseWallet);
when(commonService.getWalletByIdentifier(holderWalletBpn)).thenReturn(holderWallet);
when(walletKeyService.getPrivateKeyByWalletIdAsBytes(baseWallet.getId()))
when(walletKeyService.getPrivateKeyByWalletIdAsBytes(baseWallet.getId() ,baseWallet.getAlgorithm()))
.thenReturn(keyPair.getPrivateKey().asByte());
when(miwSettings.supportedFrameworkVCTypes()).thenReturn(Set.of("SustainabilityCredential"));
when(holdersCredentialRepository.save(any(HoldersCredential.class)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import org.eclipse.tractusx.ssi.lib.model.verifiable.credential.VerifiableCredentialSubject;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.springframework.boot.test.web.client.TestRestTemplate;
Expand Down Expand Up @@ -144,7 +145,7 @@ public static IssueFrameworkCredentialRequest getIssueFrameworkCredentialRequest
}


public static Wallet getWalletFromString(String body) throws JsonProcessingException {
public static Wallet getWalletFromString(String body) throws JsonProcessingException, JSONException {
JSONObject jsonObject = new JSONObject(body);
//convert DidDocument
JSONObject didDocument = jsonObject.getJSONObject(StringPool.DID_DOCUMENT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ void issueFrameworkCredentialTest400() throws JsonProcessingException, JSONExcep

}

private void createAndValidateVC(String bpn, String did, String type) throws JsonProcessingException {
private void createAndValidateVC(String bpn, String did, String type) throws JsonProcessingException, JSONException {
//create wallet
String baseBpn = miwSettings.authorityWalletBpn();
String defaultLocation = miwSettings.host() + COLON_SEPARATOR + bpn;
Expand Down
Loading

0 comments on commit 531d3f7

Please sign in to comment.