Search in sources :

Example 11 with OBErrorException

use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.

the class DataEventsApiController method signPayload.

/**
 * Sign the payload
 * @param obEventNotification2 {@link OBEventNotification2} to sing
 * @return String of jwt
 * @throws {@link OBErrorException}
 */
private String signPayload(OBEventNotification2 obEventNotification2) throws OBErrorException {
    try {
        log.debug("Signing the payload: {}", obEventNotification2);
        JWTClaimsSet jwtClaimsSet = JWTClaimsSet.parse(mapper.writeValueAsString(obEventNotification2));
        JSONObjectUtils.parse(mapper.writeValueAsString(obEventNotification2));
        return cryptoApiClient.signClaims(amOpenBankingConfiguration.getIssuerID(), jwtClaimsSet, false);
    } catch (JsonProcessingException | ParseException e) {
        throw new OBErrorException(OBRIErrorType.SERVER_ERROR, "Error processing the payload to sign it: {}", e.getMessage());
    }
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) ParseException(java.text.ParseException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 12 with OBErrorException

use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.

the class FilePaymentConsentsApiController method createFilePaymentConsentsConsentIdFile.

public ResponseEntity<Void> createFilePaymentConsentsConsentIdFile(String fileParam, String consentId, String authorization, String xIdempotencyKey, String xJwsSignature, DateTime xFapiAuthDate, String xFapiCustomerIpAddress, String xFapiInteractionId, String xCustomerUserAgent, HttpServletRequest request, Principal principal) throws OBErrorResponseException {
    log.trace("Received: '{}'", fileParam);
    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();
}
Also used : PaymentFile(com.forgerock.openbanking.common.model.openbanking.forgerock.filepayment.v3_0.PaymentFile) FRFileConsent(com.forgerock.openbanking.common.model.openbanking.persistence.payment.FRFileConsent) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) Date(java.util.Date)

Example 13 with OBErrorException

use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.

the class CustomRestExceptionHandler method handleHttpClientError.

// Handle any 400 error from a downstream REST service
@ExceptionHandler(value = { HttpClientErrorException.class })
protected ResponseEntity<OBErrorResponse1> handleHttpClientError(HttpClientErrorException ex, WebRequest request) {
    log.debug("HTTP client error exception from rs store", ex);
    try {
        /*
             * Quick way to handle the OB rs-store errors in rs-api with minimal impact on code. Currently, when a
             * legitimate validation error is found in rs-store, an OBErrorException is thrown.
             * However, this gets wrapped into an HttpClientErrorException by Spring Rest client meaning JSON error
             * format is lost and error code comes out of rs-api as 500.
             * This handler code attempts to parse the HttpClientErrorException message as an OBError so it can be
             * returned as a HTTP Response.
             * If there exception message is not an OBErrorResponse then it will be parsed as a generic 4xx response
             */
        OBErrorResponse1 obErrorResponse1 = new ObjectMapper().readValue(ex.getStatusText(), OBErrorResponse1.class);
        log.debug("Parsed OBErrorResponse: {} from HttpClientErrorException message", obErrorResponse1, ex);
        return ResponseEntity.status(ex.getStatusCode()).body(obErrorResponse1);
    } catch (Exception e) {
        log.debug("HttpClientErrorException is not an OBErrorResponse1.");
        /* HttpClientErrorException is not an OBErrorResponse1. but a generic 4xx failure from framework.
            It should have been rejected by TPP-facing API and not fail in a downstream microservice unless it is an internal issue.
            Therefore we can just rethrow it and will be handled as before. */
        throw ex;
    }
}
Also used : OBErrorResponse1(uk.org.openbanking.datamodel.error.OBErrorResponse1) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DynamicClientRegistrationException(com.forgerock.openbanking.common.error.exception.dynamicclientregistration.DynamicClientRegistrationException) HttpMessageConversionException(org.springframework.http.converter.HttpMessageConversionException) MissingPathVariableException(org.springframework.web.bind.MissingPathVariableException) UnsupportedOIDCGrantTypeException(com.forgerock.openbanking.model.error.UnsupportedOIDCGrantTypeException) MissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ServletRequestBindingException(org.springframework.web.bind.ServletRequestBindingException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) MethodArgumentTypeMismatchException(org.springframework.web.method.annotation.MethodArgumentTypeMismatchException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) UnsupportedOIDCAuthMethodsException(com.forgerock.openbanking.model.error.UnsupportedOIDCAuthMethodsException) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseEntityExceptionHandler(org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler)

Example 14 with OBErrorException

use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.

the class DetachedJwsVerifier method verifyDetachedJws.

public void verifyDetachedJws(String detachedJws, OBVersion obVersion, HttpServletRequest request, String oauth2ClientId) throws OBErrorException {
    if (StringUtils.isEmpty(detachedJws)) {
        log.warn("Detached signature not provided");
        throw new OBErrorException(OBRIErrorType.DETACHED_JWS_INVALID, detachedJws, "Not provided");
    }
    try {
        MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest(request);
        String body = multiReadRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        log.debug("Verify detached signature {} with payload {}", detachedJws, body);
        // obVersion is only set from 3.1.3 onwards
        if ((obVersion == null || obVersion.isBeforeVersion(v3_1_4)) && isBase64Encoded(detachedJws)) {
            log.warn("Invalid detached signature {}, {}", detachedJws, "b64 claim header not set to false in version: " + obVersion);
            throw new OBErrorException(OBRIErrorType.DETACHED_JWS_INVALID, detachedJws, "b64 claim header not set to false");
        }
        if (obVersion != null && obVersion.isAfterVersion(v3_1_3) && isB64ClaimHeaderPresent(detachedJws)) {
            log.warn("Invalid detached signature {}, {}", detachedJws, "b64 claim header must not be present in version: " + obVersion);
            throw new OBErrorException(OBRIErrorType.DETACHED_JWS_INVALID, detachedJws, "b64 claim header must not be present");
        }
        Tpp tpp = tppStoreService.findByClientId(oauth2ClientId).get();
        DirectorySoftwareStatement softwareStatement = tpp.getDirectorySoftwareStatement();
        String orgId = softwareStatement.getOrg_id();
        String softwareId = softwareStatement.getSoftware_id();
        String expectedIssuer = orgId + "/" + softwareId;
        if (tpp.getRegistrationResponse().getJwks() != null) {
            cryptoApiClient.validateDetachedJWSWithJWK(detachedJws, body, null, expectedIssuer, tpp.getRegistrationResponse().getJwks().getKeys().get(0));
        } else {
            cryptoApiClient.validateDetachedJWS(detachedJws, body, null, expectedIssuer, tpp.getRegistrationResponse().getJwks_uri());
        }
    } catch (InvalidTokenException e) {
        log.warn("Invalid detached signature {}", detachedJws, e);
        throw new OBErrorException(OBRIErrorType.DETACHED_JWS_INVALID, detachedJws, e.getMessage());
    } catch (IOException e) {
        log.error("Can't get the request body", e);
        throw new OBErrorException(OBRIErrorType.DETACHED_JWS_UN_ACCESSIBLE);
    } catch (ParseException e) {
        log.error("Can't parse JWS", e);
        throw new OBErrorException(OBRIErrorType.DETACHED_JWS_INVALID, detachedJws, e.getMessage());
    }
}
Also used : InvalidTokenException(com.forgerock.openbanking.jwt.exceptions.InvalidTokenException) MultiReadHttpServletRequest(com.forgerock.openbanking.aspsp.rs.filter.MultiReadHttpServletRequest) Tpp(com.forgerock.openbanking.model.Tpp) DirectorySoftwareStatement(com.forgerock.openbanking.model.DirectorySoftwareStatement) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) IOException(java.io.IOException) ParseException(java.text.ParseException)

Example 15 with OBErrorException

use of com.forgerock.openbanking.exceptions.OBErrorException in project openbanking-aspsp by OpenBankingToolkit.

the class AccountsApiEndpointWrapper method verifyAccountRequestStatus.

public void verifyAccountRequestStatus() throws OBErrorException {
    log.debug("verifyAccountRequestStatus() called");
    FRExternalRequestStatusCode status = getAccountRequest().getStatus();
    switch(status) {
        case AWAITINGAUTHORISATION:
            log.info("verifyAccountRequestStatus() Account request hasn't been authorised yet. Account request: {}", getAccountRequest());
            throw new OBErrorException(OBRIErrorType.ACCOUNT_REQUEST_WAITING_PSU_CONSENT, status);
        case REJECTED:
            log.info("verifyAccountRequestStatus() Account request hasn't been rejected. Account request: {}", getAccountRequest());
            throw new OBErrorException(OBRIErrorType.ACCOUNT_REQUEST_REJECTED, status);
        case REVOKED:
            log.info("verifyAccountRequestStatus() Account request was revoked. Account request: {}", getAccountRequest());
            throw new OBErrorException(OBRIErrorType.ACCOUNT_REQUEST_REVOKED, status);
        case AUTHORISED:
            log.info("verifyAccountRequestStatus() Account request is authorised. Account request: {}", getAccountRequest());
    }
}
Also used : FRExternalRequestStatusCode(com.forgerock.openbanking.common.model.openbanking.domain.account.common.FRExternalRequestStatusCode) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException)

Aggregations

OBErrorException (com.forgerock.openbanking.exceptions.OBErrorException)69 Test (org.junit.Test)20 ParseException (java.text.ParseException)19 IOException (java.io.IOException)13 OBErrorResponseException (com.forgerock.openbanking.exceptions.OBErrorResponseException)9 SignedJWT (com.nimbusds.jwt.SignedJWT)9 ResponseEntity (org.springframework.http.ResponseEntity)9 InvalidTokenException (com.forgerock.openbanking.jwt.exceptions.InvalidTokenException)8 Tpp (com.forgerock.openbanking.model.Tpp)8 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)6 PaymentConsent (com.forgerock.openbanking.common.model.openbanking.persistence.payment.PaymentConsent)5 List (java.util.List)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 AccountRequest (com.forgerock.openbanking.common.model.openbanking.persistence.account.AccountRequest)4 OIDCConstants (com.forgerock.openbanking.constants.OIDCConstants)4 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4 PermissionDenyException (com.forgerock.openbanking.common.error.exception.PermissionDenyException)3 OAuth2BearerTokenUsageInvalidTokenException (com.forgerock.openbanking.common.error.exception.oauth2.OAuth2BearerTokenUsageInvalidTokenException)3 OAuth2InvalidClientException (com.forgerock.openbanking.common.error.exception.oauth2.OAuth2InvalidClientException)3