Search in sources :

Example 31 with OBErrorException

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

the class DataEventsApiController method updateEvents.

/**
 * Update events
 * @param eventsToUpdate list of {@link FREventNotification} to update
 * @param frDataEvent the entity body {@link FRDataEvent}
 * @throws {@link OBErrorResponseException}
 */
private void updateEvents(List<FREventNotification> eventsToUpdate, FRDataEvent frDataEvent) throws OBErrorResponseException {
    try {
        frDataEvent.getObEventNotification2List().forEach(fde -> {
            Optional<FREventNotification> optionalFREventNotification = eventsToUpdate.stream().filter(e -> e.getJti().equals(fde.getJti())).findFirst();
            if (optionalFREventNotification.isEmpty()) {
                log.error("Error updating the events, the jti set in the request not match with any existing event");
                throw new RuntimeException(new OBErrorResponseException(OBRIErrorType.DATA_INVALID_REQUEST.getHttpStatus(), OBRIErrorResponseCategory.REQUEST_INVALID, OBRIErrorType.DATA_INVALID_REQUEST.toOBError1("The jti set in the request not match with any existing event")));
            }
            try {
                FREventNotification frEventNotification = optionalFREventNotification.get();
                frEventNotification.setSignedJwt(signPayload(fde));
                frPendingEventsRepository.save(frEventNotification);
            } catch (OBErrorException obErrorException) {
                throw new RuntimeException(obErrorException);
            }
        });
    } catch (RuntimeException exception) {
        throw handleError(exception);
    }
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) java.util(java.util) AMOpenBankingConfiguration(com.forgerock.openbanking.am.config.AMOpenBankingConfiguration) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Autowired(org.springframework.beans.factory.annotation.Autowired) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) OBRIErrorType(com.forgerock.openbanking.model.error.OBRIErrorType) Controller(org.springframework.stereotype.Controller) FRPendingEventsRepository(com.forgerock.openbanking.aspsp.rs.store.repository.events.FRPendingEventsRepository) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) RequestBody(org.springframework.web.bind.annotation.RequestBody) JSONObjectUtils(com.nimbusds.jose.util.JSONObjectUtils) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) OBEventNotification2(com.forgerock.openbanking.common.model.data.OBEventNotification2) CryptoApiClient(com.forgerock.openbanking.jwt.services.CryptoApiClient) FRDataEvent(com.forgerock.openbanking.common.model.data.FRDataEvent) ResponseEntity(org.springframework.http.ResponseEntity) FREventNotification(com.forgerock.openbanking.common.model.openbanking.persistence.event.FREventNotification) ParseException(java.text.ParseException) OBRIErrorResponseCategory(com.forgerock.openbanking.model.error.OBRIErrorResponseCategory) FREventNotification(com.forgerock.openbanking.common.model.openbanking.persistence.event.FREventNotification) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException)

Example 32 with OBErrorException

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

the class DataEventsApiController method createEvents.

/**
 * Create new events
 * @param frDataEvent the entity body {@link FRDataEvent}
 */
private void createEvents(FRDataEvent frDataEvent) {
    frDataEvent.getObEventNotification2List().forEach(e -> {
        try {
            FREventNotification frEventNotification = FREventNotification.builder().jti(UUID.randomUUID().toString()).signedJwt(signPayload(e)).tppId(frDataEvent.getTppId()).build();
            log.debug("Create event notification {}", frEventNotification);
            frPendingEventsRepository.save(frEventNotification);
            frDataEvent.setJti(frEventNotification.getJti());
        } catch (OBErrorException obErrorException) {
            throw new RuntimeException(obErrorException);
        }
    });
}
Also used : FREventNotification(com.forgerock.openbanking.common.model.openbanking.persistence.event.FREventNotification) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException)

Example 33 with OBErrorException

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

the class AuthorisationApiController method validateRequestParameter.

private SignedJWT validateRequestParameter(String responseType, String clientId, String state, String nonce, String scopes, String redirectUri, String requestParametersSerialised) throws OBErrorException {
    SignedJWT requestParameters;
    try {
        try {
            EncryptedJWT.parse(requestParametersSerialised);
            log.debug("Request parameter {} is encrypted (JWE).", requestParametersSerialised);
            requestParameters = cryptoApiClient.decryptJwe(requestParametersSerialised);
            requestParametersSerialised = requestParameters.serialize();
            log.debug("Request parameter {} decrypted (JWS).", requestParametersSerialised);
        } catch (ParseException | JOSEException e) {
            // If we got an exception, it means it's a JWS
            log.debug("Request parameter {} is just signed (JWS).", requestParametersSerialised);
            requestParameters = SignedJWT.parse(requestParametersSerialised);
        }
        verifyQueryParameterMatchesRequestParameterClaim(requestParameters, "client_id", clientId);
        Optional<Tpp> byClientId = tppStoreService.findByClientId(clientId);
        if (byClientId.isEmpty()) {
            throw new OBErrorException(OBRIErrorType.REQUEST_PARAMETER_JWT_FORMAT_INVALID, "Unknown client id '" + clientId + "'");
        }
        Tpp tpp = byClientId.get();
        log.debug("Validate the request parameter signature");
        boolean validated = false;
        OIDCRegistrationResponse registrationResponse = tpp.getRegistrationResponse();
        if (registrationResponse != null) {
            JWKSet jwkSet = registrationResponse.getJwks();
            if (jwkSet != null) {
                List<JWK> jwkSetKeys = jwkSet.getKeys();
                if (jwkSetKeys != null && !jwkSetKeys.isEmpty()) {
                    JWK jwk = jwkSetKeys.get(0);
                    String jwksKeys = jwk.toString();
                    log.debug("validateRequestParameters() tpp has jwksKeys as part of registraiton. They will be" + " used to validate the request parameter.");
                    cryptoApiClient.validateJwsWithJWK(requestParametersSerialised, clientId, jwksKeys);
                    validated = true;
                } else {
                    log.debug("validateRequestParameter() tpp has no jwkSetKeys; {}", tpp);
                }
            }
            if (!validated) {
                String jwks_uri = tpp.getRegistrationResponse().getJwks_uri();
                if (jwks_uri == null || jwks_uri.isBlank()) {
                    log.error("validateRequestparameters() tpp does no have a jwksKeys, or a jwks_uri in it's " + "registration details; {}", tpp);
                    throw new InvalidTokenException("Tpp does no have a jwksKeys, or a jwks_uri in it's " + "registration details");
                } else {
                    log.debug("validateRequestParameter() Validating request parameter using jwks_uri: " + "requestParametersSerialised: '{}', clientId; '{}', jwks_url: {}", requestParametersSerialised, clientId, jwks_uri);
                    cryptoApiClient.validateJws(requestParametersSerialised, clientId, jwks_uri);
                    validated = true;
                }
            }
        } else {
            log.error("validateRequestParameter() tpp has no registration response; {}", tpp);
            throw new InvalidTokenException("Tpp is not registered");
        }
        List<String> MANDATORY_CLAIMS = Arrays.asList(OpenBankingConstants.RequestParameterClaim.AUD, OpenBankingConstants.RequestParameterClaim.SCOPE, OpenBankingConstants.RequestParameterClaim.ISS, OpenBankingConstants.RequestParameterClaim.CLAIMS, OpenBankingConstants.RequestParameterClaim.RESPONSE_TYPE, OpenBankingConstants.RequestParameterClaim.REDIRECT_URI, OpenBankingConstants.RequestParameterClaim.EXP, OpenBankingConstants.RequestParameterClaim.NONCE, OpenBankingConstants.RequestParameterClaim.CLIENT_ID);
        for (String mandatoryClaim : MANDATORY_CLAIMS) {
            if (requestParameters.getJWTClaimsSet().getClaim(mandatoryClaim) == null) {
                throw new OBErrorException(OBRIErrorType.REQUEST_PARAMETER_CLAIM_MANDATORY, mandatoryClaim);
            }
        }
        verifyQueryParameterMatchesRequestParameterClaim(requestParameters, "response_type", responseType);
        verifyQueryParameterMatchesRequestParameterClaim(requestParameters, "state", state);
        verifyQueryParameterMatchesRequestParameterClaim(requestParameters, "nonce", nonce);
        verifyQueryParameterMatchesRequestParameterClaim(requestParameters, "redirect_uri", redirectUri);
        verifyScopeQueryParameterMatchesRequestParameterClaim(requestParameters, scopes);
        verifyRequestparameterClaims(requestParameters);
    } catch (ParseException | IOException e) {
        log.error("Invalid Request parameter {}. Reason: {}", requestParametersSerialised, e.getMessage(), e);
        throw new OBErrorException(OBRIErrorType.REQUEST_PARAMETER_JWT_FORMAT_INVALID, e.getMessage());
    } catch (InvalidTokenException e) {
        log.error("Invalid Request parameter {}. Reason: {}", requestParametersSerialised, e.getMessage(), e);
        throw new OBErrorException(OBRIErrorType.REQUEST_PARAMETER_JWT_INVALID, e.getMessage());
    }
    return requestParameters;
}
Also used : InvalidTokenException(com.forgerock.openbanking.jwt.exceptions.InvalidTokenException) OIDCRegistrationResponse(com.forgerock.openbanking.model.oidc.OIDCRegistrationResponse) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) Tpp(com.forgerock.openbanking.model.Tpp) JWKSet(com.nimbusds.jose.jwk.JWKSet) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) JWK(com.nimbusds.jose.jwk.JWK)

Example 34 with OBErrorException

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

the class AuthorisationApiController method verifyRequestparameterClaims.

private void verifyRequestparameterClaims(SignedJWT requestParameters) throws OBErrorException {
    JSONObject claims = null;
    try {
        JWTClaimsSet claimSet = requestParameters.getJWTClaimsSet();
        claims = new JSONObject(claimSet.getJSONObjectClaim(OIDCConstants.OIDCClaim.CLAIMS));
    } catch (ParseException pe) {
        log.info("verifyRequestparameterClaims() Could not obtain the {} claim from the request parameter.", OIDCConstants.OIDCClaim.CLAIMS);
        throw new OBErrorException(OBRIErrorType.REQUEST_PARAMETER_JWT_INVALID, "No claims obtainable from the " + "jwt");
    }
    if (!claims.containsKey(OpenBankingConstants.RequestParameterClaim.ID_TOKEN)) {
        throw new OBErrorException(OBRIErrorType.REQUEST_PARAMETER_JWT_INVALID, "No id token claims");
    }
    Map<String, Claim> idTokenClaims = validateIdToken(claims);
    validateUserInfo(claims, idTokenClaims);
}
Also used : JSONObject(com.nimbusds.jose.shaded.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) ParseException(java.text.ParseException) Claim(com.forgerock.openbanking.model.claim.Claim)

Example 35 with OBErrorException

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

the class RSEndpointWrapper method verifyAccessToken.

public void verifyAccessToken(List<String> expectedScopes, List<OIDCConstants.GrantType> expectedGrantTypes) throws OBErrorException {
    try {
        // Verify access token
        log.info("Verify the access token {}", authorization);
        accessToken = rsEndpointWrapperService.verifyAccessToken(authorization);
        String grantTypeSerialised = accessToken.getJWTClaimsSet().getStringClaim(OBConstants.OIDCClaim.GRANT_TYPE);
        if (grantTypeSerialised == null) {
            log.error("We managed to get an access token that doesn't have a grant type claim defined: {}", authorization);
            throw new OBErrorException(SERVER_ERROR, "Access token grant type is undefined");
        }
        OIDCConstants.GrantType grantType = OIDCConstants.GrantType.fromType(grantTypeSerialised);
        if (!OIDCConstants.GrantType.REFRESH_TOKEN.equals(grantType) && !expectedGrantTypes.contains(grantType)) {
            log.debug("The access token grant type {} doesn't match one of the expected grant types {}", grantType, expectedGrantTypes);
            throw new OBErrorException(OBRIErrorType.ACCESS_TOKEN_INVALID_GRANT_TYPE, grantType, expectedGrantTypes);
        }
        List<String> scopes = (List<String>) accessToken.getJWTClaimsSet().getClaim(OBConstants.OIDCClaim.SCOPE);
        if (!scopes.containsAll(expectedScopes)) {
            log.warn("The access token {} doesn't contain the scope {}", authorization, expectedScopes);
            throw new OBErrorException(OBRIErrorType.ACCESS_TOKEN_INVALID_SCOPE, expectedScopes);
        }
    } catch (ParseException e) {
        log.warn("Couldn't parse the the access token {}. It's probably not stateless and therefore, not " + "an access token generated by our ASPSP-AS", authorization);
        throw new OBErrorException(OBRIErrorType.ACCESS_TOKEN_INVALID_FORMAT);
    } catch (InvalidTokenException e) {
        log.warn("Invalid access token {}", authorization);
        throw new OBErrorException(OBRIErrorType.ACCESS_TOKEN_INVALID, e.getMessage());
    } catch (IOException e) {
        log.error("IO exception", e);
        throw new OBErrorException(SERVER_ERROR, e.getMessage());
    }
}
Also used : InvalidTokenException(com.forgerock.openbanking.jwt.exceptions.InvalidTokenException) OIDCConstants(com.forgerock.openbanking.constants.OIDCConstants) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) List(java.util.List) ParseException(java.text.ParseException) IOException(java.io.IOException)

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