Search in sources :

Example 6 with OBErrorException

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

the class RSEndpointWrapper method execute.

public ResponseEntity execute(R main) throws OBErrorResponseException {
    log.info("execute method");
    try {
        log.debug("execute() Apply filters");
        applyFilters();
        if (additionalFilter != null) {
            additionalFilter.filter(this);
        }
        log.debug("execute() Filters applied");
        log.info("execute() Call main lambda");
        ResponseEntity response = run(main);
        String tan = rsEndpointWrapperService.getTan();
        // TODO: Does this mean we create jwsSignatures for all responses to RS calls? We don't need to sign
        // requests to accounts endpoints, although I guess it doesn't hurt if we do. Just wasteful in terms of
        // processing time etc.
        String jwsSignature = rsEndpointWrapperService.generateDetachedJws(response, obVersion, tan, xFapiFinancialId);
        return ResponseEntity.status(response.getStatusCode()).header("x-jws-signature", jwsSignature).body(response.getBody());
    } catch (OBErrorException e) {
        log.warn("Verification failed", e);
        throw new OBErrorResponseException(e.getObriErrorType().getHttpStatus(), OBRIErrorResponseCategory.REQUEST_FILTER, e.getOBError());
    } catch (JsonProcessingException e) {
        log.warn("Failed to process JSON response", e);
        throw new OBErrorResponseException(HttpStatus.INTERNAL_SERVER_ERROR, OBRIErrorResponseCategory.REQUEST_FILTER, SERVER_ERROR.toOBError1());
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 7 with OBErrorException

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

the class RSEndpointWrapper method verifyMatlsFromAccessToken.

// This method ensures that the certificate used for MATLS to access the endpoint belongs to the same
// organisation that the access token provided in the request authorization header was issued to.
public void verifyMatlsFromAccessToken() throws OBErrorException {
    try {
        log.debug("verifyMatlsFromAccessToken() called");
        String oauth2ClientId = accessToken.getJWTClaimsSet().getAudience().get(0);
        // MTLS check. We verify that the certificate is associated with the expected AISP ID
        Optional<Tpp> tpp = this.tppStoreService.findByClientId(oauth2ClientId);
        UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
        if (tpp.isPresent()) {
            String authorisationNumberFromTppRecord = tpp.get().getAuthorisationNumber();
            if (!currentUser.getUsername().equals(authorisationNumberFromTppRecord)) {
                log.warn("TPP ID from account token {} is not the one associated with the certificate {}", oauth2ClientId, currentUser.getUsername());
                throw new OBErrorException(OBRIErrorType.MATLS_TPP_AUTHENTICATION_INVALID_FROM_ACCESS_TOKEN, currentUser.getUsername(), oauth2ClientId);
            }
        }
        this.oAuth2ClientId = oauth2ClientId;
        log.info("TPP AuthorizationNumber {} has been verified against X509 certificate (MTLS)", currentUser.getUsername());
    } catch (ParseException e) {
        log.warn("Access token {} doesn't look to be a JWT. You need to enable stateless", authorization);
        throw new OBErrorException(OBRIErrorType.ACCESS_TOKEN_INVALID_FORMAT);
    }
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) Tpp(com.forgerock.openbanking.model.Tpp) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) ParseException(java.text.ParseException)

Example 8 with OBErrorException

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

the class DetachedJwsVerifierTest method shouldFailToVerifyB64HeaderGivenVersionBefore3_1_4AndB64HeaderIsTrue.

@Test
public void shouldFailToVerifyB64HeaderGivenVersionBefore3_1_4AndB64HeaderIsTrue() 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_3, request, OAUTH2_CLIENT_ID), OBErrorException.class);
    // Then
    assertThat(exception).hasMessage("Invalid detached signature " + detachedJws + ". Reason: b64 claim header not set to false");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 9 with OBErrorException

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

the class DetachedJwsVerifierTest method shouldFailToVerifyDetachedJwsGivenVerificationEnabledAndJwsIsNull.

@Test
public void shouldFailToVerifyDetachedJwsGivenVerificationEnabledAndJwsIsNull() throws IOException {
    // Given
    HttpServletRequest request = mock(HttpServletRequest.class);
    // When
    OBErrorException exception = catchThrowableOfType(() -> detachedJwsVerifier.verifyDetachedJws(null, OBVersion.v3_1_3, request, OAUTH2_CLIENT_ID), OBErrorException.class);
    // Then
    assertThat(exception).hasMessage("Invalid detached signature null. Reason: Not provided");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) Test(org.junit.Test)

Example 10 with OBErrorException

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

the class FakeDataApiController method generateFakeData.

@Override
public ResponseEntity generateFakeData(@RequestParam("userId") String userId, @RequestParam("username") String username, @RequestParam(name = "profile", required = false) String profile) throws OBErrorException {
    log.debug("generateFakeData called for userId/username '{}:{}', with profile '{}' ", userId, username, profile);
    if (RANDOM_PROFILE_ID.equals(profile)) {
        log.debug("generateFakeData() generating random data");
        return ResponseEntity.status(HttpStatus.CREATED).body(generateRandomData(userId, username));
    } else {
        log.debug("generateFakeData() generating from profile '{}'", profile);
        Optional<DataConfigurationProperties.DataTemplateProfile> any = dataConfig.getProfiles().stream().filter(t -> t.getId().equals(profile)).findAny();
        if (!any.isPresent()) {
            throw new OBErrorException(OBRIErrorType.DATA_INVALID_REQUEST, "Profile '" + profile + "' doesn't exist.");
        }
        DataConfigurationProperties.DataTemplateProfile dataTemplateProfile = any.get();
        FRUserData template = getTemplate(dataTemplateProfile.getTemplate(), username);
        template.setUserName(username);
        return dataController.importUserData(template);
    }
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) FRStatementRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.statements.FRStatementRepository) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) BigDecimal(java.math.BigDecimal) FRCustomerInfo(com.forgerock.openbanking.common.model.data.FRCustomerInfo) OBReadProduct2DataProduct(uk.org.openbanking.datamodel.account.OBReadProduct2DataProduct) FRCreditDebitIndicator(com.forgerock.openbanking.common.model.openbanking.domain.account.common.FRCreditDebitIndicator) DataConfigurationProperties(com.forgerock.openbanking.common.conf.data.DataConfigurationProperties) FRBeneficiaryRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.beneficiaries.FRBeneficiaryRepository) FRStandingOrderRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.standingorders.FRStandingOrderRepository) FRAccountSubTypeCode(com.forgerock.openbanking.common.model.openbanking.domain.account.FRFinancialAccount.FRAccountSubTypeCode) FRBalanceType(com.forgerock.openbanking.common.model.openbanking.domain.account.common.FRBalanceType) com.forgerock.openbanking.common.model.openbanking.domain.account(com.forgerock.openbanking.common.model.openbanking.domain.account) Resource(org.springframework.core.io.Resource) RoundingMode(java.math.RoundingMode) DateTimeFormat(org.joda.time.format.DateTimeFormat) FRScheduledPaymentRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.scheduledpayments.FRScheduledPaymentRepository) FRAccountIdentifier(com.forgerock.openbanking.common.model.openbanking.domain.common.FRAccountIdentifier) FRAmount(com.forgerock.openbanking.common.model.openbanking.domain.common.FRAmount) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) FRProductRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.products.FRProductRepository) Slf4j(lombok.extern.slf4j.Slf4j) FROfferRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.offers.FROfferRepository) OBExternalStatementAmountType1Code(uk.org.openbanking.datamodel.account.OBExternalStatementAmountType1Code) FRBalanceRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.balances.FRBalanceRepository) FRStatementType(com.forgerock.openbanking.common.model.openbanking.domain.account.FRStatementData.FRStatementType) FRDirectDebitStatus(com.forgerock.openbanking.common.model.openbanking.domain.account.FRDirectDebitData.FRDirectDebitStatus) java.util(java.util) FRCustomerInfoAddress(com.forgerock.openbanking.common.model.data.FRCustomerInfoAddress) ClassPathResource(org.springframework.core.io.ClassPathResource) Controller(org.springframework.stereotype.Controller) ScheduledPaymentStatus(com.forgerock.openbanking.common.model.openbanking.status.ScheduledPaymentStatus) NumberFormat(java.text.NumberFormat) OBExternalAccountIdentification4Code(uk.org.openbanking.datamodel.account.OBExternalAccountIdentification4Code) Charset(java.nio.charset.Charset) FRDirectDebitRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.directdebits.FRDirectDebitRepository) FRPartyRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.party.FRPartyRepository) FRAddressTypeCode(com.forgerock.openbanking.common.model.data.FRAddressTypeCode) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) OBExternalAccountIdentification2Code(uk.org.openbanking.datamodel.payment.OBExternalAccountIdentification2Code) FRAccountTypeCode(com.forgerock.openbanking.common.model.openbanking.domain.account.FRFinancialAccount.FRAccountTypeCode) com.forgerock.openbanking.common.model.openbanking.persistence.account(com.forgerock.openbanking.common.model.openbanking.persistence.account) StreamUtils(org.springframework.util.StreamUtils) Logger(org.slf4j.Logger) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FRAccountRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.accounts.FRAccountRepository) DateTime(org.joda.time.DateTime) DecimalFormat(java.text.DecimalFormat) FRUserData(com.forgerock.openbanking.common.model.data.FRUserData) FRAccountStatusCode(com.forgerock.openbanking.common.model.openbanking.domain.account.FRFinancialAccount.FRAccountStatusCode) FRCustomerInfoRepository(com.forgerock.openbanking.common.repositories.customerinfo.FRCustomerInfoRepository) OBRIErrorType(com.forgerock.openbanking.model.error.OBRIErrorType) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) LocalDate(org.joda.time.LocalDate) FRStandingOrderStatus(com.forgerock.openbanking.common.model.openbanking.domain.account.FRStandingOrderData.FRStandingOrderStatus) HttpStatus(org.springframework.http.HttpStatus) FRTransactionRepository(com.forgerock.openbanking.aspsp.rs.store.repository.accounts.transactions.FRTransactionRepository) ResponseEntity(org.springframework.http.ResponseEntity) BufferedReader(java.io.BufferedReader) InputStream(java.io.InputStream) FRUserData(com.forgerock.openbanking.common.model.data.FRUserData) DataConfigurationProperties(com.forgerock.openbanking.common.conf.data.DataConfigurationProperties) 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