Search in sources :

Example 61 with OBErrorException

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

the class DomesticVrpPaymentsEndpointWrapperTest method fail_checkCreditorAccountIsInInstructionIfNotInConsent.

/**
 * If the CreditorAccount was not specified in the consent, the CreditorAccount must be specified in the
 * instruction.
 */
@Test
public void fail_checkCreditorAccountIsInInstructionIfNotInConsent() throws OBErrorException {
    // Given
    DomesticVrpPaymentsEndpointWrapper domesticVrpPaymentsEndpointWrapper = new DomesticVrpPaymentsEndpointWrapper(endpointWrapperService, tppStoreService, riskValidator);
    // Create the request data
    OBDomesticVRPRequest vrpRequest = OBDomesticVRPRequestTestDataFactory.aValidOBDomesticVRPRequest();
    vrpRequest.getData().getInitiation().setCreditorAccount(null);
    vrpRequest.getData().getInstruction().setCreditorAccount(null);
    // Create an FR Consent with slightly differing initiation data
    FRDomesticVRPConsent frConsent = FRVrpTestDataFactory.aValidFRDomesticVRPConsent();
    frConsent.getVrpDetails().getData().getInitiation().setCreditorAccount(null);
    // When
    OBErrorException exception = catchThrowableOfType(() -> domesticVrpPaymentsEndpointWrapper.checkCreditorAccountIsInInstructionIfNotInConsent(vrpRequest, frConsent), OBErrorException.class);
    // Then
    assertThat(exception.getObriErrorType()).isEqualTo(OBRIErrorType.REQUEST_VRP_CREDITOR_ACCOUNT_NOT_SPECIFIED);
    assertThat(exception.getOBError().getErrorCode()).isEqualTo(OBStandardErrorCodes1.UK_OBIE_RESOURCE_CONSENT_MISMATCH.toString());
}
Also used : OBDomesticVRPRequest(uk.org.openbanking.datamodel.vrp.OBDomesticVRPRequest) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) FRDomesticVRPConsent(com.forgerock.openbanking.common.model.openbanking.persistence.vrp.FRDomesticVRPConsent) Test(org.junit.Test)

Example 62 with OBErrorException

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

the class PaymentsSubmissionEndpointWrapperTest method verifyPaymentStatus_pending.

@Test
public void verifyPaymentStatus_pending() throws Exception {
    // given
    PaymentConsent payment = FRDomesticConsent.builder().status(ConsentStatusCode.PENDING).build();
    // When
    OBErrorException obErrorException = catchThrowableOfType(() -> wrapper.payment(payment).verifyPaymentStatus(), OBErrorException.class);
    assertThat(obErrorException.getObriErrorType().getHttpStatus().value()).isEqualTo(406);
    assertThat(obErrorException.getMessage()).isEqualTo("Payment invalid. Payment still pending. Payment request status: 'PENDING'");
}
Also used : PaymentConsent(com.forgerock.openbanking.common.model.openbanking.persistence.payment.PaymentConsent) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) Test(org.junit.Test)

Example 63 with OBErrorException

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.debug("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();
}
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 64 with OBErrorException

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

the class ControlSumValidator method validate.

private static void validate(PaymentFile paymentFile, BigDecimal consentControlSum, String consentId) throws OBErrorException {
    BigDecimal fileControlSum = paymentFile.getControlSum();
    log.debug("Metadata indicates expected control sum of '{}'. File contains actual control sum of '{}'", consentControlSum, fileControlSum);
    if (fileControlSum.compareTo(consentControlSum) != 0) {
        log.warn("File consent metadata indicated control sum of '{}' but found a control sum of '{}' in uploaded file", consentControlSum, fileControlSum);
        throw new OBErrorException(OBRIErrorType.REQUEST_FILE_INCORRECT_CONTROL_SUM, fileControlSum.toPlainString(), consentControlSum.toPlainString());
    }
    log.debug("File control sum count is correct for consent id: {}", consentId);
}
Also used : OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) BigDecimal(java.math.BigDecimal)

Example 65 with OBErrorException

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

the class DataApiController method generateData.

@Override
public ResponseEntity generateData(@ApiParam(value = "PSU User session") @CookieValue(value = "obri-session", required = true) String obriSession, @ApiParam(value = "The access token") @RequestHeader(name = HttpHeaders.AUTHORIZATION, required = true) String authorization, @ApiParam(value = "Data profile", required = false) @RequestParam(name = "profile", required = false) String profile, Principal principal) throws OBErrorException, OAuth2InvalidClientException, OAuth2BearerTokenUsageInvalidTokenException {
    try {
        log.debug("generateData() called");
        String tppName = psd2WithSessionApiHelperService.getTppName(principal);
        String psuName = psd2WithSessionApiHelperService.getPsuNameFromSession(obriSession);
        verifyAccessTokenAndVerifyTppIdentity(authorization, tppName);
        log.info("generateUserData() called with session for psu '{}' by tpp '{}'", psuName, tppName);
        final String defaultProfile = profile != null ? profile : dataConfig.getDefaultProfile();
        Optional<DataConfigurationProperties.DataTemplateProfile> any = dataConfig.getProfiles().stream().filter(t -> t.getId().equals(defaultProfile)).findAny();
        if (!any.isPresent()) {
            throw new OBErrorException(OBRIErrorType.DATA_INVALID_REQUEST, "Profile '" + profile + "' doesn't exist.");
        }
        if (!userDataService.deleteUserData(psuName)) {
            psuCounterEntryKPIService.pushPsuCounterEntry(PsuCounterEntry.builder().count(1l).day(DateTime.now()).build());
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(userDataService.generateUserData(psuName, defaultProfile));
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
            log.debug("TPP bad request: {}", e.getResponseBodyAsString(), e);
            throw new OBErrorException(OBRIErrorType.DATA_INVALID_REQUEST, e.getResponseBodyAsString());
        } else {
            log.error("Internal server: {}", e.getResponseBodyAsString(), e);
            throw new OBErrorException(OBRIErrorType.SERVER_ERROR);
        }
    }
}
Also used : OpenBankingConstants(com.forgerock.openbanking.constants.OpenBankingConstants) OAuth2BearerTokenUsageInvalidTokenException(com.forgerock.openbanking.common.error.exception.oauth2.OAuth2BearerTokenUsageInvalidTokenException) RequestParam(org.springframework.web.bind.annotation.RequestParam) ApiParam(io.swagger.annotations.ApiParam) Autowired(org.springframework.beans.factory.annotation.Autowired) Controller(org.springframework.stereotype.Controller) CookieValue(org.springframework.web.bind.annotation.CookieValue) RequestBody(org.springframework.web.bind.annotation.RequestBody) PsuCounterEntry(com.forgerock.openbanking.analytics.model.entries.PsuCounterEntry) Psd2WithSessionApiHelperService(com.forgerock.openbanking.common.services.security.Psd2WithSessionApiHelperService) DataConfigurationProperties(com.forgerock.openbanking.common.conf.data.DataConfigurationProperties) AccessTokenService(com.forgerock.openbanking.common.services.token.AccessTokenService) OIDCConstants(com.forgerock.openbanking.constants.OIDCConstants) HttpHeaders(org.springframework.http.HttpHeaders) DateTime(org.joda.time.DateTime) FRUserData(com.forgerock.openbanking.common.model.data.FRUserData) OBRIErrorType(com.forgerock.openbanking.model.error.OBRIErrorType) UserDataService(com.forgerock.openbanking.common.services.store.data.UserDataService) SignedJWT(com.nimbusds.jwt.SignedJWT) PsuCounterEntryKPIService(com.forgerock.openbanking.analytics.services.PsuCounterEntryKPIService) OAuth2InvalidClientException(com.forgerock.openbanking.common.error.exception.oauth2.OAuth2InvalidClientException) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) HttpStatus(org.springframework.http.HttpStatus) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Principal(java.security.Principal) CryptoApiClient(com.forgerock.openbanking.jwt.services.CryptoApiClient) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) 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