use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.
the class RCSErrorService method invalidConsentError.
public ResponseEntity<RedirectionAction> invalidConsentError(String consentContextJwt, OBErrorException obError) throws OBErrorException {
try {
Map<String, String> params = extractParams(consentContextJwt);
String redirectURL = URLDecoder.decode(params.get("redirect_uri"), "UTF-8");
String state = "";
if (params.get("state") != null) {
state = URLDecoder.decode(params.get("state"), "UTF-8");
} else {
String requestParameter = params.get("request");
if (requestParameter != null) {
SignedJWT requestParameterJwt = (SignedJWT) JWTParser.parse(requestParameter);
state = requestParameterJwt.getJWTClaimsSet().getStringClaim(OBConstants.OIDCClaim.STATE);
}
}
if (StringUtils.isEmpty(redirectURL)) {
log.warn("Null or empty redirect URL. Falling back to just throwing error back to UI");
throw obError;
}
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(redirectURL).fragment("error=invalid_request_object&state=" + state + "&error_description=" + String.format(obError.getObriErrorType().getMessage(), obError.getArgs())).encode().build();
return ResponseEntity.status(HttpStatus.OK).body(RedirectionAction.builder().redirectUri(uriComponents.toUriString()).requestMethod(HttpMethod.GET).build());
} catch (Exception e) {
log.warn("Failed to turn error into a redirect back to TPP with and Exception. " + "Falling back to just throwing error back to UI", e);
throw obError;
}
}
use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.
the class RCSConsentDecisionApiController method decision.
/**
* @param consentDecisionSerialised
* @param ssoToken
* @return
* @throws OBErrorException
*/
@Override
public ResponseEntity decision(@RequestBody String consentDecisionSerialised, @CookieValue(value = "${am.cookie.name}") String ssoToken) throws OBErrorException {
log.debug("decisionAccountSharing() consentDecisionSerialised is {}", consentDecisionSerialised);
// Send a Consent response JWT to the initial request, which is define in the code
if (consentDecisionSerialised == null || consentDecisionSerialised.isEmpty()) {
log.debug("Consent decision is empty");
return rcsErrorService.error(OBRIErrorType.RCS_CONSENT_DECISION_EMPTY);
}
ConsentDecision consentDecision;
try {
consentDecision = objectMapper.readValue(consentDecisionSerialised, ConsentDecision.class);
} catch (IOException e) {
log.error("Remote consent decisions invalid", e);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_DECISIONS_FORMAT, e.getMessage());
}
String consentRequestJwt = consentDecision.getConsentJwt();
if (consentRequestJwt == null || consentRequestJwt.isEmpty() || consentRequestJwt.isBlank()) {
log.error("Remote consent decisions invalid - consentRequestJwt is null ");
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_DECISIONS_FORMAT, "consentRequestJwt was null or " + "empty");
}
try {
try {
log.debug("Received an accept consent request");
// TODO check token but ignore if it's expired
// cryptoApiClient.validateJws(consentDecision.getConsentJwt(),
// amOpenBankingConfiguration.getIssuerID(), amOpenBankingConfiguration.jwksUri);
SignedJWT consentContextJwt = (SignedJWT) JWTParser.parse(consentRequestJwt);
boolean decision = RCSConstants.Decision.ALLOW.equals(consentDecision.getDecision());
log.debug("The decision is '{}'", decision);
// here is a good time to actually save that the consent has been approved by our resource owner
Claims claims = JwsClaimsUtils.getClaims(consentContextJwt);
String intentId = claims.getIdTokenClaims().get(OpenBankingConstants.IdTokenClaim.INTENT_ID).getValue();
String csrf = consentContextJwt.getJWTClaimsSet().getStringClaim(RCSConstants.Claims.CSRF);
String clientId = consentContextJwt.getJWTClaimsSet().getStringClaim(RCSConstants.Claims.CLIENT_ID);
List<String> scopes = new ArrayList<>(consentContextJwt.getJWTClaimsSet().getJSONObjectClaim(RCSConstants.Claims.SCOPES).keySet());
String redirectUri = consentContextJwt.getJWTClaimsSet().getStringClaim(OIDCConstants.OIDCClaim.CONSENT_APPROVAL_REDIRECT_URI);
ConsentDecisionDelegate consentDecisionDelegate = intentTypeService.getConsentDecision(intentId);
if (consentDecisionDelegate == null) {
log.error("No Consent Decision Delegate available from the intent type Service.");
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_REQUEST_INVALID, "Invalid intent ID? '" + intentId + "'");
}
// Verify consent is own by the right TPP
String tppIdBehindConsent = consentDecisionDelegate.getTppIdBehindConsent();
Optional<Tpp> isTpp = tppStoreService.findById(tppIdBehindConsent);
if (isTpp.isEmpty()) {
log.error("The TPP '{}' that created this intent id '{}' doesn't exist anymore.", tppIdBehindConsent, intentId);
return rcsErrorService.error(OBRIErrorType.RCS_CONSENT_REQUEST_NOT_FOUND_TPP, tppIdBehindConsent, intentId, clientId);
}
if (!clientId.equals(isTpp.get().getClientId())) {
log.error("The TPP '{}' created the account request '{}' but it's TPP '{}' that is trying to get" + " consent for it.", tppIdBehindConsent, intentId, clientId);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_REQUEST_INVALID_CONSENT, tppIdBehindConsent, intentId, clientId);
}
// Verify consent decision is send by the same user
Map<String, String> profile = userProfileService.getProfile(ssoToken, amOpenBankingConfiguration.endpointUserProfile, amOpenBankingConfiguration.cookieName);
String username = profile.get(amOpenBankingConfiguration.userProfileId);
String userIdBehindConsent = consentDecisionDelegate.getUserIDBehindConsent();
if (!username.equals(userIdBehindConsent)) {
log.error("The consent was associated with user '{}' but now, its user '{}' that " + "send the consent decision.", userIdBehindConsent, username);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_DECISION_INVALID_USER, userIdBehindConsent, username);
}
// Call the right decision delegate, cased on the intent type
consentDecisionDelegate.consentDecision(consentDecisionSerialised, decision);
log.debug("Redirect the resource owner to the original oauth2/openid request but this time, with the " + "consent response jwt '{}'.", consentContextJwt.toString());
String consentJwt = rcsService.generateRCSConsentResponse(rcsConfiguration, amOpenBankingConfiguration, csrf, decision, scopes, clientId);
ResponseEntity responseEntity = rcsService.sendRCSResponseToAM(ssoToken, RedirectionAction.builder().redirectUri(redirectUri).consentJwt(consentJwt).requestMethod(HttpMethod.POST).build());
log.debug("Response received from AM: {}", responseEntity);
if (responseEntity.getStatusCode() != HttpStatus.FOUND) {
log.error("When sending the consent response {} to AM, it failed to returned a 302. response '{}' ", consentJwt, responseEntity);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_RESPONSE_FAILURE);
} else if (locationContainsError(responseEntity.getHeaders().getLocation())) {
log.error("When sending the consent response {} to AM, it failed. response '{}' ", consentJwt, responseEntity);
return rcsErrorService.invalidConsentError(responseEntity.getHeaders().getLocation());
}
ResponseEntity rewrittenResponseEntity = null;
try {
rewrittenResponseEntity = jwtOverridingService.rewriteIdTokenFragmentInLocationHeader(responseEntity);
} catch (AccessTokenReWriteException e) {
log.info("decisionAccountSharing() Failed to re-write id_token", e);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_RESPONSE_FAILURE);
}
String location = rewrittenResponseEntity.getHeaders().getFirst("Location");
log.debug("The redirection to the consent page should be in the location '{}'", location);
return ResponseEntity.ok(RedirectionAction.builder().redirectUri(location).build());
} catch (JOSEException e) {
log.error("Could not generate consent context JWT", e);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_RESPONSE_FAILURE);
} catch (ParseException e) {
log.error("Could not parse the JWT", e);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_REQUEST_FORMAT);
} catch (IOException e) {
log.error("Remote consent decisions invalid", e);
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_DECISIONS_FORMAT, e.getMessage());
}
} catch (OBErrorException e) {
return rcsErrorService.invalidConsentError(consentRequestJwt, e);
}
}
use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.
the class AccountAccessConsentDecisionDelegate method consentDecision.
@Override
public void consentDecision(String consentDecisionSerialised, boolean decision) throws IOException, OBErrorException {
AccountConsentDecision accountConsentDecision = objectMapper.readValue(consentDecisionSerialised, AccountConsentDecision.class);
if (decision) {
List<FRAccount> accounts = accountsService.get(accountRequest.getUserId());
List<String> accountsId = accounts.stream().map(Account::getId).collect(Collectors.toList());
if (!accountsId.containsAll(accountConsentDecision.getSharedAccounts())) {
log.error("The PSU {} is trying to share an account '{}' he doesn't own. List of his accounts '{}'", accountRequest.getUserId(), accountsId, accountConsentDecision.getSharedAccounts());
throw new OBErrorException(OBRIErrorType.RCS_CONSENT_DECISION_INVALID_ACCOUNT, accountRequest.getUserId(), accountsId, accountConsentDecision.getSharedAccounts());
}
accountRequest.setAccountIds(accountConsentDecision.getSharedAccounts());
accountRequest.setStatus(FRExternalRequestStatusCode.AUTHORISED);
accountRequest.setStatusUpdateDateTime(DateTime.now());
accountRequestStoreService.save(accountRequest);
} else {
log.debug("The account request {} has been deny", accountRequest.getId());
accountRequest.setStatus(FRExternalRequestStatusCode.REJECTED);
accountRequest.setStatusUpdateDateTime(DateTime.now());
accountRequestStoreService.save(accountRequest);
}
}
use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.
the class FilePaymentConsentsApiController method createFilePaymentConsentsConsentIdFile.
@Override
public ResponseEntity createFilePaymentConsentsConsentIdFile(@ApiParam(value = "Default", required = true) @Valid @RequestBody String fileParam, @ApiParam(value = "ConsentId", required = true) @PathVariable("ConsentId") String consentId, @ApiParam(value = "The unique id of the ASPSP to which the request is issued. The unique id will be issued by OB.", required = true) @RequestHeader(value = "x-fapi-financial-id", required = true) String xFapiFinancialId, @ApiParam(value = "An Authorisation Token as per https://tools.ietf.org/html/rfc6750", required = true) @RequestHeader(value = "Authorization", required = true) String authorization, @ApiParam(value = "Every request will be processed only once per x-idempotency-key. The Idempotency Key will be valid for 24 hours.", required = true) @RequestHeader(value = "x-idempotency-key", required = true) String xIdempotencyKey, @ApiParam(value = "A detached JWS signature of the body of the payload.", required = true) @RequestHeader(value = "x-jws-signature", required = true) String xJwsSignature, @ApiParam(value = "The time when the PSU last logged in with the TPP. All dates in the HTTP headers are represented as RFC 7231 Full Dates. An example is below: Sun, 10 Sep 2017 19:43:31 UTC") @RequestHeader(value = "x-fapi-customer-last-logged-time", required = false) @DateTimeFormat(pattern = HTTP_DATE_FORMAT) DateTime xFapiCustomerLastLoggedTime, @ApiParam(value = "The PSU's IP address if the PSU is currently logged in with the TPP.") @RequestHeader(value = "x-fapi-customer-ip-address", required = false) String xFapiCustomerIpAddress, @ApiParam(value = "An RFC4122 UID used as a correlation id.") @RequestHeader(value = "x-fapi-interaction-id", required = false) String xFapiInteractionId, @ApiParam(value = "Indicates the user-agent that the PSU is using.") @RequestHeader(value = "x-customer-user-agent", required = false) String xCustomerUserAgent, HttpServletRequest request, Principal principal) throws OBErrorResponseException {
log.trace("Received: '{}'", fileParam);
final FRFileConsent fileConsent = fileConsentRepository.findById(consentId).orElseThrow(() -> new OBErrorResponseException(HttpStatus.BAD_REQUEST, OBRIErrorResponseCategory.REQUEST_INVALID, OBRIErrorType.PAYMENT_ID_NOT_FOUND.toOBError1()));
// If file already exists it could be idempotent request
if (!StringUtils.isEmpty(fileConsent.getFileContent())) {
if (xIdempotencyKey.equals(fileConsent.getIdempotencyKey())) {
validateIdempotencyRequest(xIdempotencyKey, fileConsent);
log.info("File already exists for consent: '{}' and has matching idempotent key: '{}'. No action taken but returning 200/OK");
return ResponseEntity.ok().build();
} else {
log.debug("This consent already has a file uploaded and the idempotency key does not match the previous upload so rejecting.");
throw new OBErrorResponseException(HttpStatus.FORBIDDEN, OBRIErrorResponseCategory.REQUEST_INVALID, OBRIErrorType.PAYMENT_ALREADY_SUBMITTED.toOBError1(fileConsent.getStatus().toOBExternalConsentStatus2Code()));
}
}
// We parse the file and check metadata against the parsed file
try {
PaymentFile paymentFile = PaymentFileFactory.createPaymentFile(fileConsent.getFileType(), fileParam);
log.info("Successfully parsed file of type: '{}' for consent: '{}'", fileConsent.getFileType(), fileConsent.getId());
FileTransactionCountValidator.validate(fileConsent, paymentFile);
ControlSumValidator.validate(fileConsent, paymentFile);
fileConsent.setPayments(paymentFile.getPayments());
fileConsent.setFileContent(fileParam);
fileConsent.setUpdated(new Date());
fileConsent.setStatus(ConsentStatusCode.AWAITINGAUTHORISATION);
fileConsent.setStatusUpdate(DateTime.now());
fileConsentRepository.save(fileConsent);
} catch (OBErrorException e) {
throw new OBErrorResponseException(e.getObriErrorType().getHttpStatus(), OBRIErrorResponseCategory.REQUEST_INVALID, e.getOBError());
}
return ResponseEntity.ok().build();
}
use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.
the class DetachedJwsVerifierTest method shouldFailToVerifyB64HeaderGivenVersion3_1_4AndB64HeaderIsPresent.
@Test
public void shouldFailToVerifyB64HeaderGivenVersion3_1_4AndB64HeaderIsPresent() throws Exception {
// Given
String detachedJws = "eyJiNjQiOnRydWUsImh0dHA6XC9cL29wZW5iYW5raW5nLm9yZy51a1wvaWF0IjoxNTk4NDMwMDA4LCJodHRwOlwvXC9vcGVuYmFua2luZy5vcmcudWtcL3RhbiI6Im9wZW5iYW5raW5nLm9yZy51ayIsImNyaXQiOlsiYjY0IiwiaHR0cDpcL1wvb3BlbmJhbmtpbmcub3JnLnVrXC9pYXQiLCJodHRwOlwvXC9vcGVuYmFua2luZy5vcmcudWtcL3RhbiIsImh0dHA6XC9cL29wZW5iYW5raW5nLm9yZy51a1wvaXNzIl0sImtpZCI6InRfSXU2eFhZRXQyeGh3TUFzX3JsYWNHeGtFWSIsImh0dHA6XC9cL29wZW5iYW5raW5nLm9yZy51a1wvaXNzIjoiaHR0cDpcL1wvb3BlbmJhbmtpbmcub3JnLnVrXC9pYXQiLCJhbGciOiJQUzI1NiJ9..yfhofJGNJfseVOEhCKanjxHlxlnMCdBKOy9HQFvMf7ZmEpkp2DiKKHJeK1LzDHYOo6WtkImIWwuTS3VvzBPrn7-z83CqM-BHZRzI-_E2I7EzaOzr8We4PtBVDk4wgwSxZW5Q0MPM-WcKgAMPskqrCVXMHLce2AcVsK6bivpi8mdSlA0rVj5FXhXw75-_fuWz8-2GY4xNF0h5YH7Tk4qpQsdpFhgpiagT29ujDcX46g5rF9mA8hUWqtJQE5yoF64S_lBUf4c_R1K1NyG5IwT-GbIoECF-epK5ybNLuD_ZfTfLcWVLI8rav0dRpiI0rdg5-upuB94H-npx1k1KsRXqSA";
HttpServletRequest request = setupHttpServletRequestMock();
// When
OBErrorException exception = catchThrowableOfType(() -> detachedJwsVerifier.verifyDetachedJws(detachedJws, OBVersion.v3_1_4, request, OAUTH2_CLIENT_ID), OBErrorException.class);
// Then
assertThat(exception).hasMessage("Invalid detached signature " + detachedJws + ". Reason: b64 claim header must not be present");
}
Aggregations