-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathIssuersCredentialService.java
389 lines (321 loc) · 17.1 KB
/
IssuersCredentialService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
* *******************************************************************************
* Copyright (c) 2021,2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
* ******************************************************************************
*/
package org.eclipse.tractusx.managedidentitywallets.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jwt.SignedJWT;
import com.smartsensesolutions.java.commons.FilterRequest;
import com.smartsensesolutions.java.commons.base.repository.BaseRepository;
import com.smartsensesolutions.java.commons.base.service.BaseService;
import com.smartsensesolutions.java.commons.criteria.CriteriaOperator;
import com.smartsensesolutions.java.commons.operator.Operator;
import com.smartsensesolutions.java.commons.sort.Sort;
import com.smartsensesolutions.java.commons.sort.SortType;
import com.smartsensesolutions.java.commons.specification.SpecificationUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.eclipse.tractusx.managedidentitywallets.command.GetCredentialsCommand;
import org.eclipse.tractusx.managedidentitywallets.config.MIWSettings;
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;
import org.eclipse.tractusx.managedidentitywallets.dao.repository.HoldersCredentialRepository;
import org.eclipse.tractusx.managedidentitywallets.dao.repository.IssuersCredentialRepository;
import org.eclipse.tractusx.managedidentitywallets.domain.CredentialCreationConfig;
import org.eclipse.tractusx.managedidentitywallets.domain.SigningServiceType;
import org.eclipse.tractusx.managedidentitywallets.domain.VerifiableEncoding;
import org.eclipse.tractusx.managedidentitywallets.dto.CredentialVerificationRequest;
import org.eclipse.tractusx.managedidentitywallets.dto.CredentialsResponse;
import org.eclipse.tractusx.managedidentitywallets.exception.ForbiddenException;
import org.eclipse.tractusx.managedidentitywallets.signing.SignerResult;
import org.eclipse.tractusx.managedidentitywallets.signing.SigningService;
import org.eclipse.tractusx.managedidentitywallets.utils.CommonUtils;
import org.eclipse.tractusx.managedidentitywallets.utils.Validate;
import org.eclipse.tractusx.ssi.lib.did.resolver.DidResolver;
import org.eclipse.tractusx.ssi.lib.did.web.DidWebResolver;
import org.eclipse.tractusx.ssi.lib.did.web.util.DidWebParser;
import org.eclipse.tractusx.ssi.lib.exception.proof.JwtExpiredException;
import org.eclipse.tractusx.ssi.lib.jwt.SignedJwtValidator;
import org.eclipse.tractusx.ssi.lib.jwt.SignedJwtVerifier;
import org.eclipse.tractusx.ssi.lib.model.verifiable.credential.VerifiableCredential;
import org.eclipse.tractusx.ssi.lib.proof.LinkedDataProofValidation;
import org.eclipse.tractusx.ssi.lib.serialization.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.net.http.HttpClient;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* The type Issuers credential service.
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class IssuersCredentialService extends BaseService<IssuersCredential, Long> {
/**
* The constant BASE_WALLET_BPN_IS_NOT_MATCHING_WITH_REQUEST_BPN_FROM_TOKEN.
*/
public static final String BASE_WALLET_BPN_IS_NOT_MATCHING_WITH_REQUEST_BPN_FROM_TOKEN = "Base wallet BPN is not matching with request BPN(from token)";
private final IssuersCredentialRepository issuersCredentialRepository;
private final MIWSettings miwSettings;
private final SpecificationUtil<IssuersCredential> credentialSpecificationUtil;
private final HoldersCredentialRepository holdersCredentialRepository;
private final CommonService commonService;
private final ObjectMapper objectMapper;
private Map<SigningServiceType, SigningService> availableSigningServices;
@Override
protected BaseRepository<IssuersCredential, Long> getRepository() {
return issuersCredentialRepository;
}
@Override
protected SpecificationUtil<IssuersCredential> getSpecificationUtil() {
return credentialSpecificationUtil;
}
/**
* Gets credentials.
*
* @param command the command
* @return the credentials
*/
public PageImpl<CredentialsResponse> getCredentials(GetCredentialsCommand command) {
FilterRequest filterRequest = new FilterRequest();
filterRequest.setSize(command.getSize());
filterRequest.setPage(command.getPageNumber());
//Issuer must be caller of API
Wallet issuerWallet = commonService.getWalletByIdentifier(command.getCallerBPN());
filterRequest.appendCriteria(StringPool.ISSUER_DID, Operator.EQUALS, issuerWallet.getDid());
if (StringUtils.hasText(command.getIdentifier())) {
Wallet holderWallet = commonService.getWalletByIdentifier(command.getIdentifier());
filterRequest.appendCriteria(StringPool.HOLDER_DID, Operator.EQUALS, holderWallet.getDid());
}
if (StringUtils.hasText(command.getCredentialId())) {
filterRequest.appendCriteria(StringPool.CREDENTIAL_ID, Operator.EQUALS, command.getCredentialId());
}
FilterRequest request = new FilterRequest();
if (!CollectionUtils.isEmpty(command.getType())) {
request.setPage(filterRequest.getPage());
request.setSize(filterRequest.getSize());
request.setCriteriaOperator(CriteriaOperator.OR);
for (String str : command.getType()) {
request.appendCriteria(StringPool.TYPE, Operator.CONTAIN, str);
}
}
Sort sort = new Sort();
sort.setColumn(command.getSortColumn());
sort.setSortType(SortType.valueOf(command.getSortType().toUpperCase()));
filterRequest.setSort(sort);
Page<IssuersCredential> filter = filter(filterRequest, request, CriteriaOperator.AND);
List<CredentialsResponse> list = new ArrayList<>(filter.getContent().size());
Wallet holderWallet = command.getIdentifier() != null ? commonService.getWalletByIdentifier(command.getIdentifier()) : issuerWallet;
for (IssuersCredential credential : filter.getContent()) {
CredentialsResponse cr = new CredentialsResponse();
if (command.isAsJwt()) {
CredentialCreationConfig config = CredentialCreationConfig.builder()
.algorithm(SupportedAlgorithms.ED25519)
.issuerDoc(issuerWallet.getDidDocument())
.holderDid(holderWallet.getDid())
.keyName(issuerWallet.getBpn())
.verifiableCredential(credential.getData())
.subject(credential.getData().getCredentialSubject().get(0))
.contexts(credential.getData().getContext())
.vcId(credential.getData().getId())
.types(credential.getData().getTypes())
.encoding(VerifiableEncoding.JWT)
.build();
SignerResult signerResult = availableSigningServices.get(issuerWallet.getSigningServiceType()).createCredential(config);
cr.setJwt(signerResult.getJwt());
} else {
cr.setVc(credential.getData());
}
list.add(cr);
}
return new PageImpl<>(list, filter.getPageable(), filter.getTotalElements());
}
/**
* Issue credential using base wallet
*
* @param holderDid the holder did
* @param data the data
* @param asJwt the as jwt
* @param callerBpn the caller bpn
* @return the verifiable credential
*/
@Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED)
public CredentialsResponse issueCredentialUsingBaseWallet(String holderDid, Map<String, Object> data, boolean asJwt, String callerBpn) {
//Fetch Holder Wallet
Wallet holderWallet = commonService.getWalletByIdentifier(holderDid);
VerifiableCredential verifiableCredential = new VerifiableCredential(data);
Wallet issuerWallet = commonService.getWalletByIdentifier(verifiableCredential.getIssuer().toString());
validateAccess(callerBpn, issuerWallet);
boolean isSelfIssued = isSelfIssued(holderWallet.getBpn());
CredentialCreationConfig holdersCredentialCreationConfig = CredentialCreationConfig.builder()
.encoding(VerifiableEncoding.JSON_LD)
.subject(verifiableCredential.getCredentialSubject().get(0))
.types(verifiableCredential.getTypes())
.issuerDoc(issuerWallet.getDidDocument())
.keyName(miwSettings.authorityWalletBpn())
.holderDid(holderWallet.getDid())
.contexts(verifiableCredential.getContext())
.expiryDate(Date.from(verifiableCredential.getExpirationDate()))
.selfIssued(isSelfIssued)
.algorithm(SupportedAlgorithms.valueOf(issuerWallet.getAlgorithm()))
.build();
// Create Credential
SignerResult result = availableSigningServices.get(issuerWallet.getSigningServiceType()).createCredential(holdersCredentialCreationConfig);
VerifiableCredential vc = (VerifiableCredential) result.getJsonLd();
HoldersCredential holdersCredential = CommonUtils.convertVerifiableCredential(vc, holdersCredentialCreationConfig);
//save in holder wallet
holdersCredential = holdersCredentialRepository.save(holdersCredential);
//Store Credential in issuers table
IssuersCredential issuersCredential = IssuersCredential.of(holdersCredential);
issuersCredential = create(issuersCredential);
final CredentialsResponse cr = new CredentialsResponse();
// Return VC
if (asJwt) {
holdersCredentialCreationConfig.setVerifiableCredential(issuersCredential.getData());
holdersCredentialCreationConfig.setEncoding(VerifiableEncoding.JWT);
SignerResult credential = availableSigningServices.get(issuerWallet.getSigningServiceType()).createCredential(holdersCredentialCreationConfig);
cr.setJwt(credential.getJwt());
} else {
cr.setVc(issuersCredential.getData());
}
log.debug("VC type of {} issued to bpn ->{}", StringEscapeUtils.escapeJava(verifiableCredential.getTypes().toString()), StringEscapeUtils.escapeJava(holderWallet.getBpn()));
return cr;
}
private JWTVerificationResult verifyVCAsJWT(String jwt, DidResolver didResolver, boolean withCredentialsValidation, boolean withCredentialExpiryDate) throws IOException, ParseException {
SignedJWT signedJWT = SignedJWT.parse(jwt);
Map<String, Object> claims = objectMapper.readValue(signedJWT.getPayload().toBytes(), Map.class);
String vcClaim = objectMapper.writeValueAsString(claims.get("vc"));
Map<String, Object> map = SerializeUtil.fromJson(vcClaim);
VerifiableCredential verifiableCredential = new VerifiableCredential(map);
//took this approach to avoid issues in sonarQube
return new JWTVerificationResult(validateSignature(withCredentialsValidation, signedJWT, didResolver) && validateJWTExpiryDate(withCredentialExpiryDate, signedJWT), verifiableCredential);
}
private record JWTVerificationResult(boolean valid, VerifiableCredential verifiableCredential) {
}
private boolean validateSignature(boolean withValidateSignature, SignedJWT signedJWT, DidResolver didResolver) {
if (!withValidateSignature) {
return true;
}
//validate jwt signature
try {
SignedJwtVerifier jwtVerifier = new SignedJwtVerifier(didResolver);
return jwtVerifier.verify(signedJWT);
} catch (Exception e) {
log.error("Can not verify signature of jwt", e);
return false;
}
}
private boolean validateJWTExpiryDate(boolean withExpiryDate, SignedJWT signedJWT) {
if (!withExpiryDate) {
return true;
}
try {
SignedJwtValidator jwtValidator = new SignedJwtValidator();
jwtValidator.validateDate(signedJWT);
return true;
} catch (Exception e) {
if (!(e instanceof JwtExpiredException)) {
log.error("Can not validate jwt expiry date ", e);
}
return false;
}
}
/**
* Credentials validation map.
*
* @param verificationRequest the verification request
* @param withCredentialExpiryDate the with credential expiry date
* @return the map
*/
public Map<String, Object> credentialsValidation(CredentialVerificationRequest verificationRequest, boolean withCredentialExpiryDate) {
return credentialsValidation(verificationRequest, true, withCredentialExpiryDate);
}
/**
* Credentials validation map.
*
* @param verificationRequest the verification request
* @param withCredentialsValidation the with credentials validation
* @param withCredentialExpiryDate the with credential expiry date
* @return the map
*/
@SneakyThrows
public Map<String, Object> credentialsValidation(CredentialVerificationRequest verificationRequest, boolean withCredentialsValidation, boolean withCredentialExpiryDate) {
HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
DidResolver didResolver = new DidWebResolver(httpClient, new DidWebParser(), miwSettings.enforceHttps());
Map<String, Object> response = new TreeMap<>();
boolean valid;
VerifiableCredential verifiableCredential;
boolean dateValidation = true;
if (verificationRequest.containsKey(StringPool.VC_JWT_KEY)) {
JWTVerificationResult result = verifyVCAsJWT((String) verificationRequest.get(StringPool.VC_JWT_KEY), didResolver, withCredentialsValidation, withCredentialExpiryDate);
valid = result.valid;
} else {
verifiableCredential = new VerifiableCredential(verificationRequest);
LinkedDataProofValidation proofValidation = LinkedDataProofValidation.newInstance(didResolver);
if (withCredentialsValidation) {
valid = proofValidation.verify(verifiableCredential);
} else {
valid = true;
}
dateValidation = CommonService.validateExpiry(withCredentialExpiryDate, verifiableCredential,
response);
}
response.put(StringPool.VALID, valid && dateValidation);
response.put(StringPool.VC, verificationRequest);
return response;
}
private void validateAccess(String callerBpn, Wallet issuerWallet) {
//validate BPN access, VC must be issued by base wallet
Validate.isFalse(callerBpn.equals(issuerWallet.getBpn())).launch(new ForbiddenException(BASE_WALLET_BPN_IS_NOT_MATCHING_WITH_REQUEST_BPN_FROM_TOKEN));
//issuer must be base wallet
Validate.isFalse(issuerWallet.getBpn().equals(miwSettings.authorityWalletBpn())).launch(new ForbiddenException(BASE_WALLET_BPN_IS_NOT_MATCHING_WITH_REQUEST_BPN_FROM_TOKEN));
}
private boolean isSelfIssued(String holderBpn) {
return holderBpn.equals(miwSettings.authorityWalletBpn());
}
/**
* Sets key service.
*
* @param availableKeyStorage the available key storage
*/
@Autowired
public void setKeyService(Map<SigningServiceType, SigningService> availableKeyStorage) {
this.availableSigningServices = availableKeyStorage;
}
}