Search in sources :

Example 46 with OBErrorException

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;
    }
}
Also used : UriComponents(org.springframework.web.util.UriComponents) SignedJWT(com.nimbusds.jwt.SignedJWT) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) ParseException(java.text.ParseException)

Example 47 with OBErrorException

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);
    }
}
Also used : Claims(com.forgerock.openbanking.model.claim.Claims) ArrayList(java.util.ArrayList) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) IOException(java.io.IOException) SignedJWT(com.nimbusds.jwt.SignedJWT) ResponseEntity(org.springframework.http.ResponseEntity) Tpp(com.forgerock.openbanking.model.Tpp) AccessTokenReWriteException(com.forgerock.openbanking.common.error.exception.AccessTokenReWriteException) ConsentDecision(com.forgerock.openbanking.common.model.rcs.consentdecision.ConsentDecision) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException)

Example 48 with OBErrorException

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);
    }
}
Also used : FRAccount(com.forgerock.openbanking.common.model.openbanking.persistence.account.FRAccount) AccountConsentDecision(com.forgerock.openbanking.common.model.rcs.consentdecision.AccountConsentDecision) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException)

Example 49 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.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();
}
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 50 with OBErrorException

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");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

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